简体   繁体   English

NodeJS使用module.exports导出异步变量

[英]NodeJS export async variable with module.exports

I have 2 files in a nodejs app: 我在nodejs应用程序中有2个文件:

export.js (reads a file line by line and saves it into an array) export.js (逐行读取文件并将其保存到数组中)

var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('test.txt')
});
var file_lines = [];

onFinish(function(result) {
    module.exports = result;
});

function onFinish(callback){
    lineReader.on('line', function (line) {

        file_lines.push(line);

    }).on('close', function() {
        callback(file_lines);
    })
};

and app.js (should get the exported values so I can play with it in here) app.js (应获取导出的值,以便在此处进行操作)

var a = require("./export");

console.log(a);

As you can see in the export.js I've used an async callback so it will save the data, but I think I'll need another async callback in the app.js file. 如您在export.js中看到的,我使用了一个异步回调,因此它将保存数据,但是我认为我将在app.js文件中需要另一个异步回调。 What would be the best way to achieve this? 实现这一目标的最佳方法是什么?

PS I realized that the async call for the export.js file isn't necessary. PS我意识到,不需要export.js文件的异步调用。 Here is the new version: 这是新版本:

var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('test.txt')
});
var file_lines = [];

lineReader.on('line', function (line) {

    file_lines.push(line);

}).on('close', function() {
    module.exports = file_lines;
    console.log(file_lines);
})

But again, my question will be, how would I get the values in the a variable in the app.js file? 但是再次,我的问题是,我如何在app.js文件的a变量中获取值?

var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('test.txt')
});
var file_lines = [];

module.exports = function onFinish(callback){
    lineReader.on('line', function (line) {

        file_lines.push(line);

    }).on('close', function() {
        callback(file_lines);
    })
};

and then 接着

var a = require("./export");

a(function(data){ console.log(data) })

Instead of a callback, you can also export a promise : 除了回调,您还可以导出promise

var Promise = require('bluebird')

var lineReader = require('readline').createInterface({
    input: require('fs').createReadStream('test.txt')
});

module.exports = function (user) {
    return new Promise(function (resolve, reject) {
        var file_lines = [];

        lineReader.on('line', function (line) {

        file_lines.push(line);

        }).on('close', function() {
            resolve(file_lines);
        })

    })
}

Then use it nicely, like this: 然后很好地使用它,如下所示:

read_lines = require('line_reader')

read_lines()
    .then(function (lines) {
        // lines are already read here
    })

to get the Promise, you can install bluebird with npm i bluebird 要获得Promise,您可以使用npm i bluebird安装npm i bluebird

您可以导出功能lineReader并设置onFinish回调函数,其中console.log可以写

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM