Feeling completely lost and stuck in a rut. Promises seemed straightforward until I actually tried to implement them. Sharing my basic code here without any promise attempts for simplicity's sake. After taking a few months hiatus from this, I returned to find myself struggling with a script that reads files line by line from a directory and adds those lines to an array. The ultimate goal is to then write all those lines to a new file.
The issue lies in the fact that the function writeAllLinesToFile is being called before the allTheLines array is populated with lines read from the directory's files. As a result, the array remains empty and nothing gets written to the new file.
I've made multiple failed attempts at solving this problem and ended up complicating my actual code further. Can anyone help me get past this obstacle?
var allTheLines = [];
function processFile(inputFile) {
var fs = require('fs');
var readline = require('readline');
var instream = fs.createReadStream(inputFile);
var outstream = new (require('stream'))();
var rl = readline.createInterface(instream, outstream);
// action to take when a line is read
rl.on('line', function (line) {
// console.log("pushing: ", line);
allTheLines.push(line);
});
// action to take when there are no more lines to read
rl.on('close', function (line) {
console.log('...end of a file');
});
}
function writeAllLinesToFile() {
var fs = require('fs');
for (var i = 0; i < allTheLines.length; i++) {
console.log("line: : ", allTheLines[i]);
fs.appendFile('./allTheLines.html', allTheLines[i] + '\n', function (err) {
if (err) throw err;
});
};
console.log("Done writing.");
}
// ***************************************
// Execution Starts Here
// ***************************************
var fs = require('fs');
fs.readdir('./filesToRead', (err, files) => {
for (var i = 0; i < files.length; i++) {
processFile('./filesToRead/' + files[i]);
console.log('file#: ', i);
};
console.log('Done processing files.');
writeAllLinesToFile();
});