javascript - Node 脚本引用错误: fs is not defined error in test script

标签 javascript node.js

我正在尝试使用 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。使用 constletvar 定义它,如下所示:

const fs = require('fs');

关于javascript - Node 脚本引用错误: fs is not defined error in test script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43171652/

相关文章:

javascript - 如何在javascript中检查php数组的长度

javascript - 无法在 sapui5 中对多个字段应用搜索

javascript - 为什么这个 jquery 传输不起作用

javascript - 我该如何处理?代码不验证 : Noscript to compensate for lack of JS, 但也适应移动用户

javascript - 根据单选按钮和复选框按钮显示/隐藏 div

javascript - Node js 应用程序中的 async.js 问题

javascript - 为什么 Typescript 在转译代码中将 .default() 添加到类构造函数中?

node.js - 在 WebMatrix 中运行 Node 应用程序时出错

node.js - 如何访问在同一Pod中运行的NodeJS服务器?

node.js - 如何为 MS Bot Builder Node SDK 机器人编写单元测试?