简体   繁体   中英

Using the shell provided with NodeJS

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?

选择一个目录,然后运行npm install express --save ,然后运行node ,最后运行var express = require('express');

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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