以讀取文件為例寸莫,首先惠险,創(chuàng)建文件a.txt
跟啤,文件內(nèi)寫入內(nèi)容Hello world!
。
回調(diào)函數(shù)寫法
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')