Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  176] [ 5]  / answers: 1 / hits: 72231  / 7 Years ago, sun, april 2, 2017, 12:00:00

I am trying out node to run a simple js script to read a file,
following is the content of my script:



use strict
fs = require('fs');
var args = process.argv.slice(2);
fs.readFile(args, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(Reading from file + args);
console.log(data);
});


when I try to run this using the following command:
node myTestFile.js testFile



I get this error:



fs = require('fs');
^
ReferenceError: fs is not defined
at Object.<anonymous> (/<Path to file>/myTestFile.js:2:4)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:393:7)
at startup (bootstrap_node.js:150:9)
at bootstrap_node.js:508:3


Isn't fs in node like a library like stdio in c ?



Do we have to explicitly define the library path somewhere in node ?



How can I get the above example to work ?


More From » node.js

 Answers
8

The problem is not require('fs'), but the left side; you'd get the same error with



fs = 42;


That's because there is no variable fs defined. Define it with const, let, or var, like this:



const fs = require('fs');

[#58299] Thursday, March 30, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daveon

Total Points: 749
Total Questions: 108
Total Answers: 87

Location: Malaysia
Member since Wed, May 11, 2022
2 Years ago
;