Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"File is not defined" error in javascript while executing from node.js command prompt

I have a javascript in which I try to read a file and just print it on the console , however it gives "File is not defined" error inspite of the file test.txt being in the same path Following is the code snippet.

var txtFile = "test.txt";
var file = new File(txtFile);
file.open("r");
var str = "";
while (!file.eof) {
    str += file.readln() + "\n";
}
console.log(str);
file.close();    
like image 743
rstalekar Avatar asked Jan 13 '18 07:01

rstalekar


People also ask

How do you fix the error require is not defined in node JS?

You are using require in a Node. If that is set to module , ES6 modules will be enabled and you will run into the error mentioned above (specifically ReferenceError: require is not defined in ES module scope, you can use import instead ). Simply remove that entry and you will be able to use require .

How do you fix the error require is not defined in JavaScript?

To solve the "ReferenceError require is not defined" error, remove the type property if it's set to module in your package. json file and rename any files that have a . mjs extension to have a . js extension.

Why is document undefined in JavaScript?

The most common reason for this error is because you're using Node. That is to say, you are trying to access the document object on the server, but the server does not have access to the document object because it lives on the browser.


1 Answers

In node.js you don't have File, but you can use the built in file-system if you require it. You can also read all the file at once with readFileSync (faster than reading it row by row).

const fs = require('fs');

let txtFile = "test.txt";
let str = fs.readFileSync(txtFile,'utf8');

console.log(str);
like image 124
some Avatar answered Oct 18 '22 06:10

some