node: Cannot find module (node installed with brew)

I try to run a script that i wrote in node. In order to debug and show you my problem, i reduced the script to:

#! /usr/bin/env node

var prompt = require('prompt');

When i try to run the script i get

module.js:340
  throw err;
        ^
Error: Cannot find module 'prompt'
  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> (/Users/derzyklop/S/dotfiles/bin/bugs:3:14)
  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)

I tried to install "prompt" with npm install prompt and also global with npm install prompt -g. But my script still doesn't work.

"prompt" seems to be installed, because npm list --depth=0 gives me

npm list

and npm list -g --depth=0 gives me

npm list -g

I installed node via brew, so the next thing i tried was that i removed node by brew remove npm and brew remove node and i downloaded the installer for OSX from here. But that didn't change anything.

I'm out of ideas. Why can't node find the module? Is it possible, that npm list -g searches at other paths than the require(..) in my script?


Update

The script is located in my personal bin-folder in ~/dotfiles/bin/myscript which is added to $PATH by export PATH=~/dotfiles/bin:$PATH.

I found out, that require() searches global modules in {prefix}/lib/node_modules, where {prefix} is npm config get prefix.

So i can temporary fix it by doing this: require('/usr/local/lib/node_modules/prompt');.

Local modules are searched in ./node_modules. In my case this must be ~/dotfiles/bin/node_modules, so i did

cd ~/dotfiles/bin/
npm install prompt

and with this i can use require('prompt'); in my script.

So the question is: How do i let my node-script search for modules in {executing directory}/node_modules? And still: Why is require() not searching in /usr/local/lib/node_modules/?

Mocha is going to be your friend here, it is the fastest way to remedy this situation. Install mocha:

$ npm install -g mocha

Also your test script is problematic. So you can make test script: test.js with the following.

var assert = require("assert")
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    })
  })
})

Then it is simple as running: mocha test.js

I tested this and I was receiving the same errors as you from node. Even if you do node test.js you will get an error. Hopefully this mocha solution works for you.

Refrences: 1. http://visionmedia.github.io/mocha/