Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS fs.readFileSync() bad arguments

I'm getting the following error in my Node and can't figure out why:

TypeError: Bad arguments
    at Object.fs.readFileSync (fs.js:277:11)
    at getSeries (/Users/user/tv/final.js:57:16)
    at /Users/user/tv/final.js:89:4
    at /Users/user/tv/node_modules/async/lib/async.js:610:21
    at /Users/user/tv/node_modules/async/lib/async.js:249:17
    at iterate (/Users/user/tv/node_modules/async/lib/async.js:149:13)
    at /Users/user/tv/node_modules/async/lib/async.js:160:25
    at /Users/user/tv/node_modules/async/lib/async.js:251:21
    at /Users/user/tv/node_modules/async/lib/async.js:615:34
    at /Users/user/tv/final.js:86:4

I'm pretty sure it has nothing to do with the async npm package I'm using as I got the same error before I started using it.

Here is the code:

    function getSeries() {
    JSON.parse(fs.readFileSync('updates.json', function(err,data) {
        if (err) {
           console.error(err);
        }
        else {
           var json = data;
        }
}));
like image 618
Roemer Avatar asked May 23 '14 09:05

Roemer


1 Answers

You are mixing asynchronous and synchronous in a bad way. You are confusing different stuff.

Your code should be either like this (synchronous):

try {
    var json = JSON.parse(fs.readFileSync('updates.json'));
} catch (err) {
    console.error(err);
}

or asynchronous:

fs.readFile('updates.json', function(err,data) {
    if (err) {
       console.error(err);
    }
    else {
       var json = JSON.parse(data);
    }
});

The difference comes that fs.readFile (docs) expects a callback and will give you the error/result by calling the callback given. It doesn't return anything.

And fs.readFileSync (docs) doesn't accept a callback, because it's synchronous and it returns the result or throws the error.

Also if you are parsing .json statically, you can use require:

var json = require('./updates')

Note that, require function will cache it's output and on the subsequent runs it will return the same object without blocking or doing any IO.

like image 117
Farid Nouri Neshat Avatar answered Oct 17 '22 23:10

Farid Nouri Neshat