node 写入文件内容
1. 在Node.js中写入文件的最简单方法是使用
fs.writeFile()
const fs=require('fs');
const content = 'this is the content';
fs.writeFile('./jiyu.txt',content,(err)=>{
if(err) {
console.error(err);
return
}
});
运行结果:
jiyu.txt 原内容是 这是node读出来的内容
运行完毕是 this is the content
2. 另外,您可以使用同步版本
fs.writeFileSync()
const fs= require('fs');
const content = 'Some content';
try {
fs.writeFileSync('./jiyu.txt',content);
}catch(err){
console.log(err);
}
运行结果:
jiyu.txt 原内容是 this is the content
运行完毕是 Some content
3.
const fs = require('fs');
const replace_content = 'repace old content';
// fs.writeFile('./jiyu.txt',replace_content,{flag:'r+'},(err)=>{});
fs.writeFile('./jiyu.txt',replace_content,{flag:'w+'},(err)=>{});
运行结果:
jiyu.txt 原内容是 this is the content
运行完毕是 Some content
4.
const fs = require('fs');
const append_content = 'append new content';
// fs.writeFile('./jiyu.txt',append_content,{flag:'a+'},(err)=>{});
fs.appendFile('./jiyu.txt',append_content,(err)=>{
if(err){
console.error(err);
return
}
});
运行结果:
jiyu.txt 原内容是 Some content
运行完毕是 Some contentappend new content'