admin管理员组文章数量:1202374
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();
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();
Share
Improve this question
edited Aug 31, 2019 at 11:50
some
49.6k14 gold badges81 silver badges95 bronze badges
asked Jan 13, 2018 at 7:17
rstalekarrstalekar
3591 gold badge2 silver badges7 bronze badges
3
|
2 Answers
Reset to default 7This question was asked and answered in January 2018, when the latest version of node.js was v7.10.1, and that version didn't have the File API.
The ReferenceError you get is because there isn't a variable named File
, and has nothing to do with the file you are trying to open.
You can test this by starting node interactively and enter File
and press enter. Or try Life
or any other word that isn't defined, and you get the error ReferenceError: <the identifier you wrote> is not defined
.
The File API isn't available in Node version 7.10.1 or Edge prior to version 79. Most major browsers released support during 2014-2015.
The Node command line environment does not implement the browser javascript's "File" class mainly due to the use-case scenarios. The browser File class was implemented for handling File inputs from form uploads.
The good news is the NodeJS project has recently merged a PR implementing support for the File class in the Node command line environment for compatibility purposes.
If you can't update to the latest NodeJS version to make use of this update, you can try using a polyfill library implementing File, however this necessitates an explicit import rather than File being implicitly available.
import {File} from '@web-std/file';
const file = new File(...
This may help you in the event your need for File is in first-party code rather than a third party library. Good luck!
版权声明:本文标题:"File is not defined" error in javascript while executing from node.js command prompt - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738650778a2104855.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
new File(txtFile)
but there is nothing that defines what File is. – some Commented Jan 13, 2018 at 7:26