So I have to parse files that are in differents directories in js and in order to do that I use a for in loop to get the data from each file. At each iteration of my loop I run fs.Readfile and then I attribute the values for the file currently being treated. But the console.log shows that I is always equals to 1 in the for loop and that data[i] is not being assigned the right values for fn, ln and dob.
This code :
var fs = require('fs');
var path = require('path');
var data = [];
var directories = fs.readdirSync('./path/to/')
.filter(file => fs.lstatSync(path.join('./path/to/', file)).isDirectory());
var fn = "";
var ln = "";
var dob = "";
var strArray;
for (var i in directories)
{
fs.readFile('./path/to/' + directories[i] + '/file.html', 'utf8', function (err, content)
{
if (err)
return console.log(err);
strArray = content.split(/([A-Z][a-z]*) ([A-Z][a-z]*) ([0-9]{2}\/[0-9]{2}\/[0-9]{4})/g);
fn = strArray[1];
ln = strArray[2];
dob = strArray[3];
console.log(fn, ln, dob, i);
});
console.log(i);
data[i] = {
id:directories[i],
fn:fn,
ln:ln,
dob:dob };
}
console.log(data);
Produce this output :
0
1
[ { id: '7X123Y23', fn: '', ln: '', dob: '' },
{ id: '7X423Y33', fn: '', ln: '', dob: '' } ]
Jean Martin 23/04/1968 1
Jeanne Martine 17/10/1972 1
Which feels pretty unlogical for me about both the content displayed and the order in which elements are displayed.
Edit
I saw the other question before, it didn't seems to work before but now i is prompted 0 then 1 when console.log(fn, ln, dob, i); is ran, but even with this working fine now, data[i] is not attributed the right values.
The new output :
0
1
[ { id: '7X123Y23', fn: '', ln: '', dob: '' },
{ id: '7X423Y33', fn: '', ln: '', dob: '' } ]
Jean Martin 23/04/1968 0
Jeanne Martine 17/10/1972 1
I've tried to change var to let for fn, ln, dob and strArray but it doesn't change anything. I come from C and I'm pretty new to js and OOP and the variable scope thing is really something I don't get.
To clarify the question, how do I get data to have this value ? :
[ { id: '7X123Y23', fn: 'Jean', ln: 'Martin', dob: '23/04/1968' },
{ id: '7X423Y33', fn: 'Jeanne', ln: 'Martine', dob: '17/10/1972' } ]