I try to read out a file with id's and return it as an array. Each row contains a single id. I would like to transfer each id to an array cell. That's my code:
var fs = require('fs');
var reader = fs.createReadStream('RTIdList.js', {encoding: 'utf8'});
reader.once( 'end' , function () {
console.log( 'Read completed successfully.' );
});
var lineReader = require('readline').createInterface({
input: reader,
});
function RTIdReader(){
var arrayPos = 0;
var idArray = new Array();
lineReader.on('line', function (line) {
console.log('Line from file:', line);
idArray[arrayPos] = line;
arrayPos++;
});
console.log('idArray[0]: '+idArray[0]);
return idArray;
}
RTIdReader();
Do you have an idea, what I'm doing wrong? AND how would it be right?
@DrakaSAN: the code works until filling the array. I'm not able to console.log or return the array. The code stops after lineReader.on
I'm struggeling since round about two weeks with callbacks. And guess, I didn't understand them. That's my try:
var fs = require('fs');
function RT(idList){
console.log('RT works');
}
function idList(){
var idArray = new Array();
var reader = fs.createReadStream('RTIdList.js', {encoding: 'utf8'});
reader.once( 'end' , function () {
console.log( 'Read completed successfully.' );
});
var lineReader = require('readline').createInterface({
input: reader,
});
return {
lineReader.on('line', function (line) {
console.log('Line from file:', line);
idArray.push(line);
return idArray;
}
}
}
RT();
Why does my callback not work?
Okay, back to the beginning. That what I started with.
var fs = require('fs');
var idArray = new Array();
var reader = fs.createReadStream('RTIdList.js', {encoding: 'utf8'});
reader.once( 'end' , function () {
console.log( 'Read completed successfully.' );
});
var lineReader = require('readline').createInterface({
input: reader,
});
lineReader.on('line', function (line) {
console.log('Line from file:', line);
idArray.push(line);
});
Where and how do I have to but the callback?