一、文件读取
node文档:http://nodejs.cn/api/fs.html#fs_fs_opensync_path_flags_mode
1.1、主要接口方法
- 导入文件模块:
require('fs');
- 同步读取文件方法:
fs.readFileSync(path[, options])
- 异步读取文件方法:
fs.readFile(path[, options], callback)
1.2、同步读取文件步骤
// 1.导入文件模块
var fs = require('fs');
// 2. 同步
var content = fs.readFileSync('hello.txt', {flag: 'r', encoding: 'utf-8'});
console.log(content)
1.3、异步读取文件步骤
// 导入文件模块
var fs = require('fs');
// 异步
var p1 = fs.readFile('hello.txt', {flag: 'r', encoding: 'utf-8'}, function(err, data) {
if(err) {
console.log(err)
}else {
console.log(data)
}
})
1.4、为异步方法封装成Promise
封装的方法
function fsReadFile (path) {
return new Promise(function (resolve, reject) {
fs.readFile(path, {flag: 'r', encoding: 'utf-8'}, function (err, data) {
if (err) {
// 失败
reject(err)
} else {
// 成功
resolve(data)
}
})
})
}
使用
- 普通使用
var p1 = fsReadFile('hello.txt');
p1.then(data => {
console.log(data)
}).catch(err => {
console.log(err)
})
console.log('123')
- 使用
await/async
async function readList() {
var file2 = await fsReadFile('hello.txt');
var file3 = await fsReadFile(file2 + '.txt');
var file3Content = await fsReadFile(file3 + '.txt');
console.log(file3Content)
}
readList()