We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
使用ES6 promise封装文件读写操作
nodejs的 fs 文件系统操作都是异步的,充满了大量的回调函数,存在难以忍受的回调地狱。 现在我们可以使用ES6 promise封装,来解决这个问题。 具体代码如下:
// fs-async.js文件 import fs from 'fs' /** * [读文件] * @param {[type]} filePath [文件路径] * @return {[type]} [description] */ export const readFile = (filePath) => { return new Promise((reslove, reject) => { fs.readFile(filePath, 'utf8', (err, data) => { if (!err) { reslove(JSON.parse(data)) } else { reject(err) } }) }) } /** * [写文件] * @param {[type]} filePath [文件路径] * @param {[type]} data [新的文件数据] * @return {[type]} [description] */ export const writeFile = (filePath, data) => { return new Promise((reslove, reject) => { fs.writeFile(filePath, JSON.stringify(data), (err) => { if (err) { reject(err) } }) }) }
封装后我们可以使用 async/await以同步的方式来读取文件内容了。
import {readFile,writeFile} from './fs-async' const getData=async()=>{ const data=await readFile('./users.json') console.log(data) } getData() //会打印出文件的内容
The text was updated successfully, but these errors were encountered:
No branches or pull requests
使用ES6 promise封装文件读写操作
nodejs的 fs 文件系统操作都是异步的,充满了大量的回调函数,存在难以忍受的回调地狱。
现在我们可以使用ES6 promise封装,来解决这个问题。
具体代码如下:
封装后我们可以使用 async/await以同步的方式来读取文件内容了。
The text was updated successfully, but these errors were encountered: