为什么我不能在Node.js shell中需要模块?

A. *_*uff 3 javascript shell node.js

用英语讲

当我尝试require在Node.js shell中加载一个模块来使用它时,我得到了一些意想不到的结果(而不是编写脚本并使用Node运行它).例如,在脚本中,我可以这样做:

var _ = require('grunt');
grunt.registerTask(/* ...*/);
Run Code Online (Sandbox Code Playgroud)

这很好用.但是当我尝试在Node.js shell中执行此操作时,除非我指定node_modules目录,否则它首先找不到该模块,然后调用其中一个模块的方法只能在它停止之前工作一次.

在Tech-Speake中

在当前目录中,我有以下子目录:

- node_modules
  - lodash
  - grunt
Run Code Online (Sandbox Code Playgroud)

现在我想使用其中一个已安装的库来使用Node.js shell:

$ node
> var _ = require('lodash');
undefined

> _ = require('./node_modules/lodash');
// Long output of function list
Run Code Online (Sandbox Code Playgroud)

现在,如果我尝试使用lodash,它会工作一次然后停止,我必须再次导入它:

_.reduce(/* ... */); //Works
_.reduce(/* ... */); // TypeError: Cannot call method 'reduce' of undefined
Run Code Online (Sandbox Code Playgroud)

nit*_*gar 12

_由于var名称不起作用,因为Node使用它来保存上一次操作的结果.尝试类似的东西:

> var l = require('lodash'); 
> l.reduce(/* ... */);
Run Code Online (Sandbox Code Playgroud)

  • @ A.Duff`_`仅包含REPL中上一个操作的结果.在剧本中没有多大意义; 如果您需要访问结果,您可以将其分配给某些内容. (2认同)