I have 3 Json file in my project/Folder
file1.json
JavaScript
x
9
1
{
2
"id":"01",
3
"name":"abc",
4
"subject":[
5
"subject1":"Maths",
6
"subject2":"Science"
7
]
8
}
9
File2.json
JavaScript
1
9
1
{
2
"id":"01",
3
"name":"dummy",
4
"Degree":[
5
"Graduation":"BCom",
6
"Post Graduation":"MBA"
7
]
8
}
9
File3.json
JavaScript
1
9
1
{
2
"id":"BA01",
3
"Address":"India",
4
"P Address":[
5
"State":"MP",
6
"City":"Satna"
7
]
8
}
9
I wrote a code where I can read my project/Folder so I can read all the data which is present inside the json file and want to append in my output.json
JavaScript
1
33
33
1
fs.readdir(
2
path.join(process.cwd(), "project/Folder"),
3
(err, fileNames) => {
4
if (err) throw console.log(err.message);
5
// Loop fileNames array
6
fileNames.forEach((filename) => {
7
// Read file content
8
fs.readFile(
9
path.join(
10
process.cwd(),
11
"project/Folder",
12
`${filename}`
13
),
14
(err, data) => {
15
if (err) throw console.log(err.message);
16
// Log file content
17
const output = JSON.parse(data);
18
fs.appendFile(
19
path.join(
20
process.cwd(),
21
"project/Folder",
22
`output.json`
23
),
24
`[${JSON.stringify(output)},]`,
25
(err) => {
26
if (err) throw console.log(err.message);
27
}
28
);
29
}
30
);
31
});
32
}
33
);
my expected output is like this as I want to append the data which I got from file1, file2, file3 json in output.json
JavaScript
1
12
12
1
[
2
{
3
file1.json data
4
},
5
{
6
file2.json data
7
},
8
{
9
file3.json data
10
}
11
]
12
but in reality I am getting this as an output
JavaScript
1
16
16
1
[
2
{
3
file1.josn data
4
},
5
]
6
[
7
{
8
file2.josn data
9
},
10
]
11
[
12
{
13
file3.josn data
14
},
15
]
16
I don’t know how can I achieve my expected output like this even I wrote code properly but I think I am missing something, but I don’t know what can someone help me to achieve my expected code?
JavaScript
1
12
12
1
[
2
{
3
file1.json data
4
},
5
{
6
file2.json data
7
},
8
{
9
file3.json data
10
}
11
]
12
Advertisement
Answer
JavaScript
1
26
26
1
const arr = [];
2
3
fs.readdir(path.join(process.cwd(), "project/Folder"), (err, fileNames) => {
4
if (err) throw console.log(err.message);
5
// Loop fileNames array
6
fileNames.forEach((filename) => {
7
// Read file content
8
fs.readFile(
9
path.join(process.cwd(), "project/Folder", `${filename}`),
10
(err, data) => {
11
if (err) throw console.log(err.message);
12
// Log file content
13
const output = JSON.parse(data);
14
arr.push(output);
15
fs.writeFileSync(
16
path.join(process.cwd(), "project/Folder", `output.json`),
17
JSON.stringify(arr),
18
(err) => {
19
if (err) throw console.log(err.message);
20
}
21
);
22
}
23
);
24
});
25
});
26
maybe like this, push it to an array and then save it to a new file