简体   繁体   English

如何使用全局 nodejs 模块?

[英]How to use a global nodejs module?

I got the following error when I try to use esprima.当我尝试使用 esprima 时出现以下错误。 Does anybody know how to fix the problem?有谁知道如何解决这个问题? Thanks.谢谢。

$ npm install -g esprima
/usr/local/bin/esparse -> /usr/local/lib/node_modules/esprima/bin/esparse.js
/usr/local/bin/esvalidate -> /usr/local/lib/node_modules/esprima/bin/esvalidate.js
+ esprima@4.0.1
updated 1 package in 0.837s
$ cat main.js 
#!/usr/bin/env node
// vim: set noexpandtab tabstop=2:

var esprima = require('esprima');
var program = 'const answer = 42';
 
console.log(esprima.tokenize(program));
console.log(esprima.parseScript(program));
$ node main.js 
internal/modules/cjs/loader.js:960
  throw err;
  ^

Error: Cannot find module 'esprima'
Require stack:
- /private/tmp/main.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:957:15)
    at Function.Module._load (internal/modules/cjs/loader.js:840:27)
    at Module.require (internal/modules/cjs/loader.js:1019:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.<anonymous> (/private/tmp/main.js:4:15)
    at Module._compile (internal/modules/cjs/loader.js:1133:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
    at Module.load (internal/modules/cjs/loader.js:977:32)
    at Function.Module._load (internal/modules/cjs/loader.js:877:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/private/tmp/main.js' ]
}

I think you installed esprima module in global node_modules.我认为您在全局 node_modules 中安装了esprima模块。
If you want to use esprima in main.js which is located at /private/temp/main.js ,如果你想在位于/private/temp/main.js esprima中使用/private/temp/main.js
you should run npm install esprima in /private/temp/ without -g你应该在/private/temp/不带-g情况下运行npm install esprima

EDIT - How to require global modules编辑 - 如何要求全局模块

Way 1方式一

I assume you're in mac system.我假设你在mac系统中。
Before you run your main.js, run export NODE_PATH=/usr/local/lib/node_modules in the shell , not node.js program.在你运行你的main.js,运行export NODE_PATH=/usr/local/lib/node_modulesshell ,不Node.js的程序。
Then you could require the global modules by const esprima = require("esprima") .然后你可以通过const esprima = require("esprima")来要求全局模块。

By the way, global modules position could be different in the different system.顺便说一下,全局模块的位置在不同的系统中可能会有所不同。

Way 2方式二

After you knew your global modules position,在你知道你的全球模块位置之后,
you could require it by const esprima = require("/usr/local/lib/node_modules/esprima")你可以通过const esprima = require("/usr/local/lib/node_modules/esprima")来要求它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM