我正在尝试使用 Node 运行一个简单的js脚本来读取文件, 以下是我的脚本的内容:
"use strict"
fs = require('fs');
var args = process.argv.slice(2);
fs.readFile(args, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log("Reading from file " + args);
console.log(data);
});
当我尝试使用以下命令运行它时: Node myTestFile.js testFile
我收到此错误:
fs = require('fs');
^
ReferenceError: fs is not defined
at Object.<anonymous> (/<Path to file>/myTestFile.js:2:4)
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
node 中的 fs 不是像 c 中的 stdio 这样的库吗?
我们是否必须在 Node 中的某个位置显式定义库路径?
我怎样才能让上面的例子工作?
最佳答案
问题不在于require('fs')
,而是左侧;你会得到同样的错误
fs = 42;
那是因为没有定义变量fs。使用 const
、let
或 var
定义它,如下所示:
const fs = require('fs');
关于javascript - Node 脚本引用错误: fs is not defined error in test script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43171652/