【Node.js】写入文件
2019-07-06 本文已影响3人
德育处主任

node.js的写入文件和读取文件一样,都是分为同步和异步。
- 同步写入:
fs.writeFileSync()
- 异步写入:
fs.writeFile()
同步写入
let fs = require('fs');
fs.writeFileSync('write.txt', 'Hello Rabbit!');
代码一执行,在同一个目录中就会生成 write.txt
文件。并且内容为:Hello Rabbit!
。


异步写入
let fs = require('fs');
fs.writeFile('write.txt', "HELLO RABBIT~~~", (err) => {
if(err) throw err;
console.log('写入成功');
})
console.log(123);
异步会比同步多一个回调函数。
这个回调函数只有一个 err
参数。如果出现错误可以通过 err
获取错误信息。
最后一行输出 123
,是为了测试异步。
