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;
}
}));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With