覆盖写入
var fs = require("fs");
console.log("准备写入文件");
fs.writeFile('input.txt', '我是通 过fs.writeFile 写入文件的内容', function(err) {
if (err) {
return console.error(err);
}
console.log("数据写入成功!");
console.log("--------我是分割线-------------")
console.log("读取写入的数据!");
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("异步读取文件数据: " + data.toString());
});
});
追加写入
换行: \n
\r\n
// 示例Node.js程序将数据追加到文件
var fs = require('fs');
var data = "\r\nLearn Node.js with the help of well built Node.js Tutorial.";
// 将数据附加到文件
fs.appendFile('sample.txt',data, 'utf8',
// 回调函数
function(err) {
if (err) throw err;
// 如果没有错误
console.log("Data is appended to file successfully.")
});