Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
If I read a JSON file by just
fs.readFileSync(filename, 'utf-8')
it works, but when I add error handling, I get
undefined
.
const fs = require('fs');
let ruleTemplate;
fs.readFileSync('cmdCreateRule.json', 'utf8', function (err, data) {
if (err) {
throw err;
} else {
ruleTemplate = JSON.parse(data);
console.log(ruleTempate);
Question
Can anyone see why ruleTemplate
becomes undefined
?
–
readFileSync
does not accept a callback function. It only accepts two arguments. The third argument (where you are passing your function which assigns a value to ruleTemplate
) is ignored.
readFileSync
returns a string or buffer.
As Quentin said, this is a synchronous function, so it does not get a callback as parameter, try this:
const fs = require('fs');
let ruleTemplate;
try {
fs.readFileSync('cmdCreateRule.json', 'utf8');
ruleTemplate = JSON.parse(data);
catch (err) {
throw err;
console.log(ruleTempate);
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.