1.异步读取
function fsRead(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, { flag: 'r', encoding: 'utf-8' }, function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
}
调用:
async function ReadList() {
let w1 = await fsRead('hello.txt')
}
ReadList()
2.异步写入
function writes(path,content) {
return new Promise((resolve,reject)=>{
fs.writeFile(path, content, { flag: 'a', encoding: 'utf-8' }, function (err) {
if (err) {
console.log('写入出错');
reject(err)
} else {
console.log('写入成功');
resolve()
}
})
})
}
调用:
async function writeList() {
await writes('lhy.html','<h1>1今天七月1日</h1>')
await writes('lhy.html','<h1>2明天七月2日</h1>')
}
writeList()