node.jsesprima

How to use a global nodejs module?


I got the following error when I try to use 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' ]
}

Solution

  • I think you installed esprima module in global node_modules.
    If you want to use esprima in main.js which is located at /private/temp/main.js,
    you should run npm install esprima in /private/temp/ without -g

    EDIT - How to require global modules

    Way 1

    I assume you're in mac system.
    Before you run your main.js, run export NODE_PATH=/usr/local/lib/node_modules in the shell, not node.js program.
    Then you could require the global modules by 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")