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'