【问题标题】:node.js require doesn't work in script?node.js 要求在脚本中不起作用?
【发布时间】:2013-11-12 18:13:58
【问题描述】:

我有一个名为 /tmp/test.js 的小节点脚本,其中包含:

console.log(require("w3cjs"));

如果我在命令提示符下执行此操作:

nvm use v0.10.21
node /tmp/test.js

我得到这个输出:

module.js:340
    throw err;
      ^
Error: Cannot find module 'w3cjs'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/tmp/test.js:1:75)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

但如果我这样做:

node -e $(cat /tmp/test.js)

我得到这个输出:

{ validate: [Function: validate],
  setW3cCheckUrl: [Function: setW3cCheckUrl],
  w3cjs: [Circular] }

(换句话说 - 它有效。)

为什么会有差异以及如何使脚本工作?

【问题讨论】:

  • 我猜那个节点不喜欢被/tmp-ed
  • 您的w3cjs 模块可能已本地安装到特定目录。 Node 使用安装在执行文件目录中的本地模块。当您使用-e 时,Node 会使用安装在您当前目录中的本地模块。
  • @apsillers - 如果你回答这个问题,我会投赞成票。

标签: javascript node.js


【解决方案1】:

当您在不同目录中运行脚本时,Node 会在该脚本目录的 node_modules 文件夹中查找本地模块。

假设你的 shell 的工作目录当前是/projects/foo。当你运行node /tmp/test.js 时,Node 在/tmp/node_modules 中查找模块,而不是在/projects/foo/node_modules 中。

但是,如果您不运行脚本文件,而是在命令行中使用-e 运行一些文本,Node 将在您的shell 当前工作目录中检查本地模块文件夹,即/projects/foo/node_modules

您的工作目录中似乎安装了w3cjs,但/tmp 中没有。你应该在那里安装它,或者install the module globally with npm's -g option

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多