node.js-0030,文件读写操作
Node API文档: https://nodejs.org/dist/latest-v10.x/docs/api/fs.html#fs_fs_writefile_file_data_options_callback
1、文件写入
// 导入fs模块
const fs = require('fs');
// 写入String
var message = '第一个文件写入,hello world!';
// helloworld.txt 写入的文件名称
// message 写入的内容 可以是String 和buffer(byte数组)
// 配置项
// 回调函数
fs.writeFile('helloworld.txt', message, (err)=>{
// err为null表示成功
if(err){
console.log('文件写入失败,错误信息:' + err);
} else {
console.log('文件写入成功!');
}
})
// 写入buffer
const data = new Uint8Array(Buffer.from('Hello Node.js'));
fs.writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
helloworld.txt
message.txt
2、文件读取
const fs = require('fs');
// helloworld.txt 被读取的文件
// 配置参数,传了utf8 data默认就被转为字符,否则为字节,需要调用toString()方法
// 回调函数
fs.readFile('helloworld.txt', (err, data) => {
if (err) throw err;
console.log(data.toString());
});
效果
还没有评论,来说两句吧...