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 ?
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');
As mentioned in the log
ReferenceError: fs is not defined
You have a ReferenceError you can define the JS
const fs = require('fs');
or
var fs = require('fs');
and declare the fs before using it.
const or var depend on the javascript syntax you are using to build your application
// Define the `fs` at the beginning of the script
const fs = require('fs');
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