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

110
Visualizações
why this function is not returning the data. it showing only undefine while print it out

I just tried to make one function that will take CSV files and return JSON data. when I console out the data it will work fine but when I tried to return the same data it will return undefined.

var fs = require('fs');

//sorting the json...
function compareStrings(a, b) {
  a = a.toLowerCase();
  b = b.toLowerCase();

  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

//reding csv and converting it into json..........
var csv_to_json = ()=>{
    fs.readFile('./Data/book.csv',(err,data)=>{
        let jsonData = [];
        var content = data.toString().split('\n').join().split('\r');
        var key = content[0].split(';');
        content.shift();

        content.forEach((item)=>{
            var temp = item.replace(",").split(';');
            var data = {}
            for(var i=0;i<key.length;i++){
                data[key[i]] = temp[i]
            }

            jsonData.push(data);
        })

        jsonData.sort(function(a, b) {
            return compareStrings(a.title, b.title);
        })

    // console.log is working fine but when I tried to return the same data it won't work properly

        // console.log(jsonData);
        return jsonData;
    })
}

console.log(csv_to_json())
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because you use a callback function and when use callback function you code execute asynchronously

I suggest you read this document

You have to change code like that:

var fs = require('fs');

//sorting the json...
function compareStrings(a, b) {
  a = a.toLowerCase();
  b = b.toLowerCase();

  return (a < b) ? -1 : (a > b) ? 1 : 0;
}

//reding csv and converting it into json..........
var csv_to_json = (callback)=>{
    fs.readFile('./Data/book.csv',(err,data)=>{
        let jsonData = [];
        var content = data.toString().split('\n').join().split('\r');
        var key = content[0].split(';');
        content.shift();

        content.forEach((item)=>{
            var temp = item.replace(",").split(';');
            var data = {}
            for(var i=0;i<key.length;i++){
                data[key[i]] = temp[i]
            }

            jsonData.push(data);
        })

        jsonData.sort(function(a, b) {
            return compareStrings(a.title, b.title);
        })

    // console.log is working fine but when I tried to return the same data it won't work properly

        // console.log(jsonData);
        callback(null, jsonData);
    })
}

csv_to_json((error, data) => {
  console.log(data);
})
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