Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node script ReferenceError: fs is not defined error in test script

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 ?

like image 377
Dhairya Seth Avatar asked Apr 02 '17 18:04

Dhairya Seth


3 Answers

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');
like image 60
phihag Avatar answered Oct 21 '22 01:10

phihag


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

like image 20
Amila Weerasinghe Avatar answered Oct 21 '22 01:10

Amila Weerasinghe


// Define the `fs` at the beginning of the script
const fs = require('fs');
like image 35
Diana Avatar answered Oct 21 '22 02:10

Diana