1 //1.加载文件操作模块,fs 模块
2 var fs = require('fs');
3
4 //2.实现文件写入操作
5 var msg = "hello world,你好世界";
6
7 //调用 fs.writeFile() 进行文件写入
8 // fs.writeFile() 是异步方法
9 // fs.writeFile('写入文件的路径','要写入的数据','文档编码格式','回调函数')
10 fs.writeFile('hello.txt', msg, 'utf8', (err) => {
11 //如果 err===null,表示文件写入
12 //只要 err 里面不是null,就表示写入文件失败了!
13 if (err) {
14 console.log('写入文件出错拉!具体错误:' + err)
15 } else {
16 console.log('ok');
17 }
18 });
1 //1.加载文件操作模块,fs 模块
2 var fs = require('fs');
3
4 //2.调用 fs.readFile() 方法来读取文件
5 // fs.readFile('读取文件的路径','文件编码格式','回调函数')
6 //在读取文件的时候,如果传递了编码格式,那么回调函数中的 data默认就会转换为 字符串,否则data 参数的数据是一个 Buffer 对象,里面保存的就是一个一个的字节(理解为字节数组)
7 //把 Buffer 对象转换为字符串,调用 toString() 方法
8
9 fs.readFile('./hello.txt', 'utf8', (err, data) => {
10 if (err) {
11 throw err;
12 } else {
13 console.log(data);
14 }
15 });
1.读取文件中的路径问题
./ 相对路径,相对的执行 node 命令的路径,而不是相对于正在执行的这个 js 文件来查找 hello.txt
解决在文件读取中 ./ 相对路径的问题
解决方法:使用 __dirname、__filename
__dirname:表示,当前正在执行的 js 文件所在的目录
___filename:表示,当前正在执行的 js 文件的完整路径
// console.log(__dirname); C:\Users\zhuyujie\Desktop\nodejs\1.fs
// console.log(__filename); C:\Users\zhuyujie\Desktop\nodejs\1.fs\2.fs_readFile.js