nodejs文件系统模块常用api操作
一、文件常用的api操作:
首先,需要引入文件系统模块:
const fs = require('fs');
1.fs.readFile(path[, options], callback)
作用:异步地读取文件的全部内容。
用法:
注:
1)回调会传入两个参数 (err, data),其中 data 是文件的内容。
2)如果没有指定字符编码,则返回原始的 buffer。
3)如果 options 是字符串,则它指定字符编码:
fs.readFile('/etc/passwd', 'utf8', callback);
例如:
新建一个hello.txt文件:
hello world!
新建一个file_test.js文件,来读取hello.txt文件的内容:
const fs = require('fs');
fs.readFile('./hello.txt',(err,data) => {
if (err) throw err;
console.log(data.toString());
})
运行结果:
2.fs.writeFile(file, data[, options], callback)
当 file 是文件名时,则异步地写入数据到文件(如果文件已存在,则覆盖文件)。 data 可以是字符串或 buffer。
例如:
新建一个file_test.js文件,在hello.txt文件中写入内容‘this is a test.’:
const fs = require('fs');
fs.writeFile('./hello.txt','this is a test.',err => {
if (err) throw err;
console.log('写入成功!');
})
运行结果:
3.fs.appendFile(path, data[, options], callback)
异步地追加数据到文件,如果文件尚不存在则创建文件。 data 可以是字符串或 Buffer。
例如:
新建一个file_test.js文件,在hello.txt文件中追加内容’hello world’:
const fs