Node.JS fs.readFileSync () bad arguments

I get 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 am sure this has nothing to do with the async npm package that I use, since I have the same error before I start 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; } })); 
+6
source share
1 answer

You mix asynchronous and synchronous wrong. You are confusing different things.

Your code should be the same (synchronously):

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

or asynchronously:

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

The difference is that fs.readFile ( docs ) is expecting a callback and will give you an error / result by calling the specified callback. It does not return anything.

And fs.readFileSync ( docs ) does not accept the callback because it is synchronous and returns a result or throws an error.

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

 var json = require('./updates') 

Note that the require function will cache its output, and in subsequent runs it will return the same object without blocking or performing any I / O.

+12
source

Source: https://habr.com/ru/post/969745/


All Articles