以读取文件为例,首先,创建文件a.txt
,文件内写入内容Hello world!
。
回调函数写法
const fs = require('fs')
fs.readFile('./a.txt', 'utf-8', (err, data) => {
if (err) throw err
console.log(data)
})
Promise写法
const fs = require('fs')
function getTxt (path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf-8', (err, data) => {
if (err) reject(err)
resolve(data)
})
})
}
getTxt('./a.txt')
.then(rst => console.log(rst))
bluebird写法
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))
fs.readFileAsync('./a.txt', 'utf-8')
.then(data => console.log(data))
Generator写法
const fs = require('fs')
function getTxt (path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf-8', (err, data) => {
if (err) reject(err)
resolve(data)
})
})
}
function * fun () {
yield getTxt('./a.txt')
}
const run = fun()
run.next().value.then(data => console.log(data))
async/await写法
const fs = require('fs')
function getTxt (path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf-8', (err, data) => {
if (err) reject(err)
resolve(data)
})
})
}
async function run (params) {
const file = await getTxt(params)
console.log(file)
return file
}
run('./a.txt')