Anonymous function passed to readFileSync is not returning any data

后端 未结 2 844
庸人自扰
庸人自扰 2021-01-26 21:01

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 ano

相关标签:
2条回答
  • 2021-01-26 21:24

    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);
        }
    };
    
    function doSomething(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 = new csv();
    
    var test =csvHandler.csvFileToArray('test.csv', ',');
    console.log(test);
    

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

    0 讨论(0)
  • 2021-01-26 21:34

    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.

    0 讨论(0)
提交回复
热议问题