问题
I'm calling a function on the server side that opens a csv file and searches for a string in each line. On the close event, the function should return an array that contains the first 5 string matches from the csv file (in the first column). However, it seems the array is unaccessible outside the function (possibly due to asynchronous behaviour):
index.js
function calling_function()
{
var a_string = "foo";
var array = database_search(a_string);
console.log(array);
}
function database_search(a_string)
{
var result = ["", "", "", "", ""];
var csv_file = readline.createInterface({
input: fs.createReadStream(__dirname + '/Static/a_file.csv')
});
var cntr = 0;
csv_file.on('line', function (line) {
if(line.indexOf(a_string) > -1)
{
if(cntr < 5)
{
result[cntr] = line.split(",")[0];
}
else
{
csv_file.close();
}
cntr++;
}
});
csv_file.on('close', function() {
return result; // not returning result array
});
}
What would be the correct way to access an array outside the readline on close event?
回答1:
In the "csv_file.on" event you are in the scope of a callback function. In order to get the array you can do the following:
function calling_function()
{
var a_string = "foo";
var array = []
database_search(a_string ,arr => {
array = arr
console.log(array);
});
}
function database_search(a_string ,callback)
{
var result = ["", "", "", "", ""];
var csv_file = readline.createInterface({
input: fs.createReadStream(__dirname + '/Static/a_file.csv')
});
var cntr = 0;
csv_file.on('line', function (line) {
if(line.indexOf(a_string) > -1)
{
if(cntr < 5)
{
result[cntr] = line.split(",")[0];
}
else
{
csv_file.close();
}
cntr++;
}
});
// notice i added the 'result' in the callback function parameter
csv_file.on('close', function(result) {
callback(result)
});
}
来源:https://stackoverflow.com/questions/52914673/return-array-from-node-js-readline-module-on-close-event