如何导出从Node.js模块异步加载的日期

时间:2019-09-19 14:48:43

标签: node.js module async.js

我在以下模块fetch.js中苦苦挣扎,该模块调用一个在多个文件中生成输出的子进程。我希望此模块返回包含该输出的JSON。

    var util = require('util');
    const path = require('path');
    const fs = require('fs');

    const path1 = path.resolve(__dirname, 'out', 'file1');
    const path2 = path.resolve(__dirname, 'out', 'file2');

    let out1, out2;

    function generate() {
       var spawn = require('child_process').spawn;
       var prog = spawn('prog', [<arguments>]);

       prog.on('exit', function (code) {
       if (code != 0) {
           console.log('Compilation failed.');
       } else {
          out1 = fs.readFileSync(path1, 'utf8');
          out2 = fs.readFileSync(path2, 'utf8');
       }
    })

    prog.stderr.on('data', function (data) {
       console.log(data);
    })


    return {out1, out2}
}


module.exports = new Promise(function(resolve, reject) {
   resolve(generate());
});

我主要执行以下操作

const promise = require('./fetch');
promise.then((o1, o2) => {
   console.log('O = ' + typeof o1);
})

我知道问题是发生的返回发生在out1和out2获取它们的值。如何纠正? TIA

1 个答案:

答案 0 :(得分:0)

您可以从generate函数本身返回promise,并导出generate函数。

const path = require('path');
const fs = require('fs');
function generate() {
  return new Promise((res, rej) => {
    const spawn = require('child_process').spawn;
    const prog = spawn('prog', []);

    prog.on('exit', function (code) {
      if (code != 0) {
        rej('Compilation failed');
      } else {
        const path1 = path.resolve(__dirname, 'out', 'file1');
        const path2 = path.resolve(__dirname, 'out', 'file2');
        const out1 = fs.readFileSync(path1, 'utf8');
        const out2 = fs.readFileSync(path2, 'utf8');
        res({ out1, out2 })
      }
    })
    prog.stderr.on('data', function (data) {
      console.log(data);
    })
  })
}


module.exports = generate;

现在,当您使用它时,可以将其用作:

const fetch = require('./fetch');
fetch()
.then(data=>{
  ....
});