This code works, I just need help with argument passing.
Goal:
To pass arguments to promises while iterating through a for loop. The arguments to pass are named folder, subfolder, pastsearch. The promises are called p1 and p2
What the Code does
This code works. Each promise takes a search term, looks for it in its file and returns "yes" or "non" if file is there or not.
Promise.all prints a single line of yes/non to a file and prints the total count of "yes" to another file.
CODE
const fs = require('fs');
const readline = require('readline')
const task_id = 1;
let folder = 1;
let subfolder = 1;
let pastsearch = 1;
const myarray = [6567, 50105, 67637, 293697];
const mylen = myarray.length;
const myfiles = ['file_1.txt', 'file_2.txt'];
fs.writeFile('/pathtomyfile/', '', function() {
console.log('done')
})
fs.writeFile('/pathtomyfile/', '', function() {
console.log('done')
})
const p1 = new Promise((resolve, reject) => {
let lineCount = 0;
let v = 0;
let yesnon = "non";
let readStream = readline.createInterface({
input: fs.createReadStream('/pathtofile/round_' + task_id + '/threehundred_' + folder + '/' + subfolder + '/' + myfiles[0], 'utf8')
});
readStream.on("line", (line) => {
lineCount++;
if (line == pastsearch) {
yesnon = "yes";
v++;
}
});
readStream.on('end', () => {
console.log('end');
readStream.destroy();
});
readStream.on("close", () =>
resolve({
yesnon
})
)
});
const p2 = new Promise((resolve, reject) => {
let readStream = readline.createInterface({
input: fs.createReadStream('/pathtofile/round_' + task_id + '/threehundred_' + folder + '/' + subfolder + '/' + myfiles[1], 'utf8')
});
let lineCount = 0;
let v = 0;
let yesnon = "non";
readStream.on("line", (line) => {
lineCount++;
if (line == pastsearch) {
yesnon = "yes";
v++;
}
});
readStream.on('end', () => {
console.log('end');
readStream.destroy();
});
readStream.on("close", () =>
resolve({
yesnon
}))
});
for (let h = 0; h < 3; h++) {
folder++
subfolder++
pastsearch = myarray[h];
Promise.all([p1, p2]).then((results) => {
const output = results.map(({
yesnon
}) => yesnon).join(' ');
fs.appendFileSync('/pathtofile/plain_round' + task_id + '.txt', output + "\n", 'utf8');
const output2 = results.map(({
yesnon
}) => yesnon);
let count = 0;
function countValues(array, countItem) {
array.forEach(itm => {
if (itm == countItem) count++;
});
return count;
}
const myresult34 = countValues(output2, "yes");
fs.appendFileSync('/pathtofile/round' + task_id + '.txt', myresult34 + "\n", 'utf8');
});
}
Note:
I am new to nodejs, mostly php experience, so I wrote this the best that I could from studying stackoverflow Q/A Posts.