Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

108
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda