3

I have a small node script named /tmp/test.js containing this:

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

If I do this from the command prompt:

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

I get this output:

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)

But if I do this:

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

I get this output:

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

(In other words - it works.)

Why the difference and how do I make the script work?

3
  • I guess that node doesn't like to be /tmp-ed Commented Nov 1, 2013 at 14:18
  • 2
    Your w3cjs module is probably locally installed to a specific directory. Node uses the local modules installed within the directory of executed file. When you use -e, Node uses the local modules installed in your current directory. Commented Nov 1, 2013 at 14:24
  • @apsillers - If you made that an answer, I'd vote for it. Commented Nov 1, 2013 at 14:27

1 Answer 1

9

When you run a script in a different directory, Node looks for local modules in the node_modules folder of that script's directory.

Suppose your shell's working directory is currently /projects/foo. When you run node /tmp/test.js, Node looks for modules in /tmp/node_modules, not in /projects/foo/node_modules.

However, if you don't run a script file, but run some text on the command line with -e, Node will check for a local module folder in your shell's current working directory, i.e., /projects/foo/node_modules.

It appears that you have w3cjs installed in your working directory, but not at /tmp. You should either install it there, or install the module globally with npm's -g option.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.