-3

Created a file with the name of index.js and the code is

var x = require("fs");
console.log("Hello");
fs.writeFileSync("text.txt","Hello");

and when I run it I receive an error:

ReferenceError: fs is not defined
at Object.<anonymous> (G:\web\Node Js\index.js:3:1)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
usman mughal
  • 189
  • 1
  • 3
  • 7

2 Answers2

2

should be var fs = require('fs');

Writing files in Node.js

Rony Nguyen
  • 1,067
  • 8
  • 18
0

The issue is caused by mismatch of variables. You've required the module in variable x and trying to access the module using varibale fs which is undefined.

You must use same variable name.

var fs = require("fs");
console.log("Hello");
fs.writeFileSync("text.txt","Hello");

or

var x = require("fs");
console.log("Hello");
x.writeFileSync("text.txt","Hello");