Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 341
garmur Avatar asked Jul 06 '12 14:07

garmur


2 Answers

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.

like image 151
Michelle Tilley Avatar answered Nov 15 '22 20:11

Michelle Tilley


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.

like image 35
Michael Yagudaev Avatar answered Nov 15 '22 21:11

Michael Yagudaev