Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

请问一下怎么在读完文件后,函数内返回文件内容

$
0
0
const fs = require('fs');
const path = require('path');

exports.music = function() {
  pathname = path.resolve(__dirname, '../config/lyric.json');

  let promise = new Promise((resolve, reject) => {
    fs.readFile(pathname, {
      encoding: 'utf8'
    }, (err, data) => {
      if(err) reject(err);

      data = JSON.parse(data);
      resolve(data);
    });
  })
    .then((data) => {
      console.log(data);  // 这个 data 怎么返回到外面
    }, (err) => {
      console.log(err);
    });
};

异步读取有办法实现吗,是否只能用同步?


Viewing all articles
Browse latest Browse all 14821

Trending Articles