[Node.js] Write or Append to a File in Node.js with fs.writeFile and fs.writeFileSync
2024-09-29 22:36:44
In node.js, you can require fs
, and then call fs.writeFile
with the filename, and data to write to that file (as a string or a buffer). That will overwrite the entire file, so to just append that data to the file instead, pass an options object with the flag
key set to a
. Or, you can use fs.appendFile
. Make sure to handle errors using a callback as the last argument to writeFile
and appendFile
.
There are synchronous versions of each function as well, fs.writeFileSync
and fs.appendFileSync
, which will throw errors, instead of returning them in a callback.
const fs = require('fs') const contents = 'Data to write 123\n' // Write File, async:
fs.writeFile('output.txt', contents, {
// flag: 'a' // 'a' flag for append
}, (err) => {
console.log("ERROR: ", err)
}) // Append File, async:
fs.appendFile('output.txt', contents, (err) => {
console.log("ERROR: ", err)
}) // Write File, Sync:
fs.writeFileSync('output.txt', contents) // Append File, Sync:
fs.appendFileSync('output.txt', contents) // Sync Error example:
try {
fs.appendFileSync('output.txt', contents, {
flag: 'ax'
})
} catch(e) {
console.log("ERROR: ", e)
} console.log("\nEnd of script")
最新文章
- Nodejs reactjs服务端渲染优化SEO
- Java中对List集合内的元素进行顺序、倒序、随机排序的示例代码
- FusionCharts 相关知识
- javascrip 分享到
- 基于异步的MVC webAPI控制器
- Entity Framewor中的 Migration
- C# 利用ajax实现局部刷新
- TF-IDF学习(python实现)
- Vue.js2.0中的变化(持续更新中)
- C++面试基础之回调
- 极简】如何在服务器上安装SSL证书?
- 006-mac下finder操作
- Github安全整理(转载)
- vue 踩坑-事件修饰符
- Mac下配置Oracle数据库客户端远程连接数据库服务器
- log4j每天,每小时产生一日志文件
- Spring_AOP动态代理详解(转)
- Swift 无操作时自动登出
- Nginx概述、安装及配置详解
- 浅谈PCA