Using the shell provided with NodeJS

84 views Asked by At

Once you've installed NodeJS, you'll have a executable in your computer named NodeJS which is a shell. I was wondering what can I do with that... here you're able to run JS code as, for example, in the browser's console, great.

Now, is it possible to require modules in that env? Doing so, I'd be able to run some JS code using functions provided by those modules which IMO would be really, really great.

I've tried installing the modules with the -g option (for example npm install -g express); then (in that shell) I want to run require('express') but it doesen't work, it says:

Error: Cannot find module 'express' at Function.Module._resolveFileName ...

Ideas?

3

There are 3 answers

1
Darkhogg On BEST ANSWER

As per issue #5431, looks like the Node.JS REPL doesn't find globally-installed modules and this is expected behaviour.

In the article linked from that issue, it reads:

  1. If you’re installing something that you want to use in your program, using require('whatever'), then install it locally, at the root of your project.

This is your case, sou need to install express locally:

$ npm install express
$ node
> var express = require('express');
undefined

Note that you get undefined as a result because of the var statement, but it did work.

0
Andy Gaskell On

Pick a directory, then run npm install express --save, then node, and finally var express = require('express');

1
Manu Artero On

Answers above are correct. Just want to add another point: going to the folder where the executable is, you'll find there the directory node_modules

nodejs
|-------node_modules
|        |-----------npm
|-------node
|-------more staff

If you paste any folder of a module inside node_modules it'll be able to be required in the nodeJS shell.

Anyway, I prefer the other solution instead to CTR-C + CTRL-V.