如何在全局范围内使csv文件到多维数组的结果可用?

时间:2020-12-03 21:35:56

If I have a global array:

如果我有一个全局数组:

    var people = [];

And I have the following function:

我有以下功能:

function readFile() {
     var IN = require('ya-csv');
     var filePath = 'data.csv';
     var reader = IN.createCsvFileReader(filePath, {
          'separator': ','
     });
     reader.on('data', function(item) {
          people.push(item);
     });
}

The people array only seems scoped inside reader.on. How can I use the people array globally?

人员阵列似乎只限于读者内部。如何在全局范围内使用people数组?

1 个解决方案

#1


1  

Your code is perfectly right if the people variable is declared outside the readFile function, which seems to be the case.

如果在readFile函数之外声明了people变量,那么你的代码是完全正确的,这似乎就是这种情况。

I guess that your problem is something like this:

我猜你的问题是这样的:

var people = [];

function readFile() {
  var IN = require('ya-csv');
  var filePath = 'data.csv';
  var reader = IN.createCsvFileReader(filePath, {
    separator: ',' // quotes around property name are optional
  });
  reader.on('data', function(item) {
    people.push(item);
  });
}

readFile();
console.log(people); // <- people is empty

This behaviour is absolutely normal. As ya-csv process incoming data asynchronously, you have to wait for processing to be finished.

这种行为绝对正常。由于ya-csv异步处理传入数据,您必须等待处理完成。

That's the purpose of the end event, triggered by CsvReader when it has finished (unfortunately not documented on ya-csv documentation)

这是结束事件的目的,由CsvReader完成后触发(遗憾的是没有记录在ya-csv文档中)

Refactoring like this will work better:

像这样重构会更好:

// make filePath a parameter, and use a callback function
function readFile(filePath, callback) {
  // make people scoped to readFile()
  var people = [];
  var IN = require('ya-csv');
  var reader = IN.createCsvFileReader(filePath, {
    separator: ',' // quotes around property name are optional
  });

  // data is emitted for each processed line
  reader.on('data', function(item) {
    // closure magic: people is accessible because current function is nested into readFile()
    people.push(item);
  });

  // end event
  reader.on('end', function() {
    // return results to caller, simply by invoking the callback.
    // by convention, first argument is an error, which is null it no problem occured
    callback(null, people);
  });

  // error handling
  reader.on('error', function(err) {
    // stop listening on events, to avoid continuing queuing data
    reader.removeAllListeners();
    // report to caller the error.
    callback(err);
  }
}

readFile('data.csv', function(err, results) {
  if (err) {
    // error handling
    return ...
  }
  // nominal case: use results that contains peoples !
  console.dir(results);
});

Please ask question with comments if something is not clear.

如果不清楚,请提出问题和评论。

== EDIT ==

==编辑==

Alternatively, you can use a variable outside readFile()

或者,您可以在readFile()之外使用变量

// notice: people is declared outside readFile
var people = []

// make filePath a parameter, and use a callback function
function readFile(filePath, callback) {
  var IN = require('ya-csv');
  var reader = IN.createCsvFileReader(filePath, {
    separator: ',' // quotes around property name are optional
  });

  // data is emitted for each processed line
  reader.on('data', function(item) {
    // closure magic: people is accessible because current function is nested into readFile()
    people.push(item);
  });

  // end event: directly invoke callback
  reader.on('end', callback);

  // error handling
  reader.on('error', function(err) {
    // stop listening on events, to avoid continuing queuing data
    reader.removeAllListeners();
    // report to caller the error.
    callback(err);
  }
}

readFile('data.csv', function(err) {
  if (err) {
    // error handling
    return ...
  }
  // you cannot use people before here, because you have no garantie that read process is finished.
  console.dir(people);
});

The drawback of this code is that calling readFile() multiple times will enqueue in the same variable, which is not modular nor reliable.

这段代码的缺点是多次调用readFile()会在同一个变量中排队,这个变量不是模块化的,也不是可靠的。

#1


1  

Your code is perfectly right if the people variable is declared outside the readFile function, which seems to be the case.

如果在readFile函数之外声明了people变量,那么你的代码是完全正确的,这似乎就是这种情况。

I guess that your problem is something like this:

我猜你的问题是这样的:

var people = [];

function readFile() {
  var IN = require('ya-csv');
  var filePath = 'data.csv';
  var reader = IN.createCsvFileReader(filePath, {
    separator: ',' // quotes around property name are optional
  });
  reader.on('data', function(item) {
    people.push(item);
  });
}

readFile();
console.log(people); // <- people is empty

This behaviour is absolutely normal. As ya-csv process incoming data asynchronously, you have to wait for processing to be finished.

这种行为绝对正常。由于ya-csv异步处理传入数据,您必须等待处理完成。

That's the purpose of the end event, triggered by CsvReader when it has finished (unfortunately not documented on ya-csv documentation)

这是结束事件的目的,由CsvReader完成后触发(遗憾的是没有记录在ya-csv文档中)

Refactoring like this will work better:

像这样重构会更好:

// make filePath a parameter, and use a callback function
function readFile(filePath, callback) {
  // make people scoped to readFile()
  var people = [];
  var IN = require('ya-csv');
  var reader = IN.createCsvFileReader(filePath, {
    separator: ',' // quotes around property name are optional
  });

  // data is emitted for each processed line
  reader.on('data', function(item) {
    // closure magic: people is accessible because current function is nested into readFile()
    people.push(item);
  });

  // end event
  reader.on('end', function() {
    // return results to caller, simply by invoking the callback.
    // by convention, first argument is an error, which is null it no problem occured
    callback(null, people);
  });

  // error handling
  reader.on('error', function(err) {
    // stop listening on events, to avoid continuing queuing data
    reader.removeAllListeners();
    // report to caller the error.
    callback(err);
  }
}

readFile('data.csv', function(err, results) {
  if (err) {
    // error handling
    return ...
  }
  // nominal case: use results that contains peoples !
  console.dir(results);
});

Please ask question with comments if something is not clear.

如果不清楚,请提出问题和评论。

== EDIT ==

==编辑==

Alternatively, you can use a variable outside readFile()

或者,您可以在readFile()之外使用变量

// notice: people is declared outside readFile
var people = []

// make filePath a parameter, and use a callback function
function readFile(filePath, callback) {
  var IN = require('ya-csv');
  var reader = IN.createCsvFileReader(filePath, {
    separator: ',' // quotes around property name are optional
  });

  // data is emitted for each processed line
  reader.on('data', function(item) {
    // closure magic: people is accessible because current function is nested into readFile()
    people.push(item);
  });

  // end event: directly invoke callback
  reader.on('end', callback);

  // error handling
  reader.on('error', function(err) {
    // stop listening on events, to avoid continuing queuing data
    reader.removeAllListeners();
    // report to caller the error.
    callback(err);
  }
}

readFile('data.csv', function(err) {
  if (err) {
    // error handling
    return ...
  }
  // you cannot use people before here, because you have no garantie that read process is finished.
  console.dir(people);
});

The drawback of this code is that calling readFile() multiple times will enqueue in the same variable, which is not modular nor reliable.

这段代码的缺点是多次调用readFile()会在同一个变量中排队,这个变量不是模块化的,也不是可靠的。