Reputation: 262
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.
Upvotes: 11
Views: 4489
Reputation: 5308
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.
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).
Upvotes: 0
Reputation: 159095
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.
Upvotes: 20
Reputation: 6129
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.
Upvotes: 1