简体   繁体   中英

Which modules does Node.js 'require' automatically?

Quick question, but one I surprisingly couldn't find the answer for with a bit of Googling... when I use the node interactive interpreter, I can type in the names of basically all core modules and see them output as objects onto the console... however, I understand that the core modules aren't all included like this by default when running a .js file.

Can anyone clear this up for me? All help appreciated.

Starting in Node 0.8, repl.js defines a list of built-in libraries that will be automatically required when you type their name on the REPL:

exports._builtinLibs = ['assert', 'buffer', 'child_process', 'cluster',
  'crypto', 'dgram', 'dns', 'events', 'fs', 'http', 'https', 'net',
  'os', 'path', 'punycode', 'querystring', 'readline', 'repl',
  'string_decoder', 'tls', 'tty', 'url', 'util', 'vm', 'zlib'];

...

if (exports._builtinLibs.indexOf(cmd) !== -1) {
  var lib = require(cmd);
  if (cmd in self.context && lib !== self.context[cmd]) {
    self.outputStream.write('A different "' + cmd +
                            '" already exists globally\n');
  } else {
    self.context._ = self.context[cmd] = lib;
    self.outputStream.write(self.writer(lib) + '\n');
  }
  self.displayPrompt();
  return;
}

This is specifically a function of repl.js , and does not work at all in any way when writing your own Node.js programs; there, you must specifically require anything you want to use.

You need to require all modules you want to use in node. Nothing other than functions included in javascript specification (ECMA spec) is included in Node.js.

To get access to the core libraries you need to require them. For example if you need access to the the create server function you need to do the following:

var http = require('http');

http.createServer(function(req, res) {
   console.log(req);
}).listen(3000);

You can also do this in the interactive console. That is assign the module to a variable and start using it afterwards.

At the moment there is a npm package that wraps around the repl.js file and gives you the list in a more friendly way.

builtin-modules

I suppose this may be interesting to quickly get that list in a scenario of having different node version (nvm), having those versions different core modules (that actually happens with different versions of AngularJS).

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