lensh / vue-qq

🎨 Vue family bucket with socket.io and express/koa2 , create a web version of mobile QQ, supporting real-time group chat, real-time private chat, special care, shielding chat, smart IP geographic location, real-time display temperature and other QQ core functions
MIT License
917 stars 231 forks source link

使用ES6 promise封装文件读写操作 #5

Open lensh opened 7 years ago

lensh commented 7 years ago

使用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()     //会打印出文件的内容