我在linereader.on中对我的数组所做的更改在外面不可用

时间:2017-03-24 15:51:06

标签: javascript

我逐行解析数据文件(包含json数据)并创建对象。然后我将这些对象添加到我在外面声明的数组中。但出于某种原因,我的服务'数组在linereader.on函数外面再次变空。我能够在linereader.on中调试console.log(服务)并看到它按预期打印数据。但是我不知道为什么它在外面再次变空了!

const getLineReader = function () {
  return require('readline').createInterface({
    input: require('fs').createReadStream('data.txt')
  });
};

const getSystem = function () {
  const lineReader = getLineReader();
  const services = [];

  lineReader.on('line', function (line) {
    const serviceJSON = JSON.parse(line);
    const tests = serviceJSON.tests.map(test => {
      return new ServiceTest(
        test.id,
        test.name,
        test.criticality);
    });

    const service = new NewService(new UniqueID(), serviceJSON.name, tests, new Timestamp());

    services.push(service);
    console.log(services); // prints Services { _services: [relevant data here] }

  });

console.log(services); // prints Services { _services: [] }

1 个答案:

答案 0 :(得分:1)

您需要收听readline 'close'事件,然后打印数组。一旦读完所有行,将调用close

lineReader.on('close', function() {
   console.log(services)
});

然后你会得到类似的东西:

const getSystem = function () {
    const lineReader = getLineReader();
    const services = [];

    lineReader.on('line', function (line) {
        const serviceJSON = JSON.parse(line);
        const tests = serviceJSON.tests.map(test => {
            return new ServiceTest(
            test.id,
            test.name,
            test.criticality);
        });

        const service = new NewService(new UniqueID(), serviceJSON.name, tests, new Timestamp());

        services.push(service);
        console.log(services); // prints Services { _services: [relevant data here] }
    });

    lineReader.on('close', function() {
        console.log(services)
    });
}

在您当前的代码中,console.log(services)会在行lineReader.on('line', ...)代码之前触发。