[Node.js] Write or Append to a File in Node.js with fs.writeFile and fs.writeFileSync

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Node.js] Write or Append to a File in Node.js with fs.writeFile and fs.writeFileSync相关的知识,希望对你有一定的参考价值。

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
‘

// 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("
End of script")

 

以上是关于[Node.js] Write or Append to a File in Node.js with fs.writeFile and fs.writeFileSync的主要内容,如果未能解决你的问题,请参考以下文章

使用 stdin.write() 将 ctrl+c 发送到 node.js 生成子进程?

Node.js——异步上传文件

如何在 Node.js 中使用 Sequelize 运行 AND 和 Or 运算符

node.js报错“Error: EBUSY: resource busy or locked, stat“

在node.js和GraphicsMagick中将tiff转换为jpeg

node.js 错误 - throw new TypeError('first argument must be a string or Buffer');