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();
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 .
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.
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.
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);
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