Exception throw referencerrror: fs is not defined in NodeJs

Dung Do Tien Jan 19 2022 113

Hello guys, I have a small project with Nodejs and I want to read and get all data from a .txt file. I used fs package as below:

fs = require('fs');
fs.open('/data/product.txt', 'wx', (err, fd) => {
  if (err) {
    if (err.code === 'EXIST') {
      console.error('product already exists');
      return;
    }

    throw err;
  }

  console.log(fd);
});

When running the above code I got an exception throw: ReferenceError: fs is not defined.

fs = require('fs');
   ^
ReferenceError: fs is not defined
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

I really installed fs package by running command npm i fs.

I'm using Node v12.18.3. 

Thank you for any suggestions.

Have 1 answer(s) found.
  • H

    Ho Minh Chien Jan 19 2022

    You can try to you var, const or let to declare fs variable. You can try to replace:

    fs = require('fs');

    to

    var fs = require('fs');

    It's really worked for me.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close