Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
unable to create array from multiple files data

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Instead of toString(), you should use JSON.stringify().

To see their different behavior, you can try this snippet:

var jsonArr = [{name: "Mia"}, {name: "Eddie"}];

// toString()
console.log(jsonArr.toString());

// JSON.stringify()
console.log(JSON.stringify(jsonArr));

JavaScript Array.prototype.toString() just prints out the elements of the array, excluding the array bracket, but JSON.stringify() prints whole Javascript object structure as a valid JSON.

As the fs.writeFile() in Node.JS needs/consumes buffer, so you need to store the JSON string result in a variable before using it.

let jsonArr = [{name: "Mia"}];
const jsonString = JSON.stringify(jsonArr);
fs.writeFile("data.json", jsonString, (err) => ...);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda