I've 2 files as below.
f1.json
{
"name":"user1"
}
f2.json
{
"name":"user2"
}
and here is my code snippet.
var fs = require("fs");
function readIt() {
let combined = [];
fs.readdir("jsonfiles", function (err, files) {
files.forEach(function (file, index) {
combined.push(fileread("jsonfiles/" + file));
});
fs.writeFile("test.json", combined.toString(), (err) => {
if (err) console.log(err);
console.log("Successfully Written to File.");
});
});
}
function fileread(filename) {
var contents = fs.readFileSync(filename);
return contents;
}
readIt();
when I run this, the resulting output is as below
{
"name":"user1"
},
{
"name":"user2"
}
but I want it to be
[
{
"name":"user1"
},
{
"name":"user2"
}
]
Please let me know where I'm going wrong.
Thanks