Skip to content Skip to sidebar Skip to footer

Anonymous Function Passed To Readfilesync Is Not Returning Any Data

I have writen simple JS object which has function csvFileToArray. Function should return parsed CSV array. The problem is that I don't have output from anonymous function which is

Solution 1:

You are using readFileSync function and it's working sync. So you can not use callback inside it. DOC

So you can use it like:

var passwdArray = [];
var csv = function () {
    this.csvFileToArray = function (fileName, delimiter) {
        console.log("test1");
        var fs = require('fs');
        var data = fs.readFileSync(fileName, 'utf8');
        var returnedData = doSomething(null,data);
        console.log(returnedData);
    }
};

functiondoSomething(err, data) {
    console.log("test2");
    if (err)  {
        throw err;
    } else {
        var csvLineArray = data.split("\n");
        var csvArray = [];
        csvArray['header'] = csvLineArray[0].split(delimiter);
        csvArray['data'] = [];
        for(var i = 1; i < csvLineArray.length; i++) {
            csvArray['data'].push(csvLineArray[i].split(delimiter));
        }
        return csvArray;
    }
};

var csvHandler = newcsv();

var test =csvHandler.csvFileToArray('test.csv', ',');
console.log(test);

If you want to use it async you can use readFile function.

Solution 2:

Are you mixing up fs.readFileSync(path[, options]) and fs.readFile(path[, options], callback)File System | Node.js v8.1.4 Documentation ?

The method you are using does not accept a callback parameter.

Post a Comment for "Anonymous Function Passed To Readfilesync Is Not Returning Any Data"