nodejs/src/node.js

618 lines
18 KiB
JavaScript
Raw Normal View History

2010-12-02 12:11:23 -08:00
(function(process) {
2010-12-02 12:11:23 -08:00
global = this;
global.process = process;
global.global = global;
global.GLOBAL = global;
global.root = global;
2010-12-02 12:11:23 -08:00
/** deprecation errors ************************************************/
2010-12-02 12:11:23 -08:00
function removed(reason) {
return function() {
throw new Error(reason);
};
}
2010-12-02 12:11:23 -08:00
process.debug =
removed('process.debug() use console.error() instead');
process.error =
removed('process.error() use console.error() instead');
process.watchFile =
removed('process.watchFile() has moved to fs.watchFile()');
process.unwatchFile =
removed('process.unwatchFile() has moved to fs.unwatchFile()');
process.mixin =
removed('process.mixin() has been removed.');
process.createChildProcess =
removed('childProcess API has changed. See doc/api.txt.');
process.inherits =
removed('process.inherits() has moved to sys.inherits.');
process._byteLength =
removed('process._byteLength() has moved to Buffer.byteLength');
process.assert = function(x, msg) {
if (!x) throw new Error(msg || 'assertion error');
};
var Script = process.binding('evals').Script;
var runInThisContext = Script.runInThisContext;
var runInNewContext = Script.runInNewContext;
2010-11-21 14:20:22 -08:00
2010-12-02 12:11:23 -08:00
// lazy loaded.
var constants;
function lazyConstants() {
if (!constants) constants = process.binding('constants');
return constants;
}
2010-11-21 14:20:22 -08:00
2010-12-02 12:11:23 -08:00
// nextTick()
2010-12-02 12:11:23 -08:00
var nextTickQueue = [];
2010-12-02 12:11:23 -08:00
process._tickCallback = function() {
var l = nextTickQueue.length;
if (l === 0) return;
2010-12-02 12:11:23 -08:00
try {
for (var i = 0; i < l; i++) {
nextTickQueue[i]();
}
}
2010-12-02 12:11:23 -08:00
catch (e) {
nextTickQueue.splice(0, i + 1);
if (i + 1 < l) {
process._needTickCallback();
}
throw e; // process.nextTick error, or 'error' event on first tick
}
2010-12-02 12:11:23 -08:00
nextTickQueue.splice(0, l);
};
2010-12-02 12:11:23 -08:00
process.nextTick = function(callback) {
nextTickQueue.push(callback);
process._needTickCallback();
};
2010-12-02 12:11:23 -08:00
// This contains the source code for the files in lib/
// Like, natives.fs is the contents of lib/fs.js
var natives = process.binding('natives');
// Module System
2011-01-12 22:05:45 +01:00
var Module = (function() {
2010-12-02 12:11:23 -08:00
function Module(id, parent) {
this.id = id;
this.exports = {};
this.parent = parent;
this.filename = null;
this.loaded = false;
this.exited = false;
this.children = [];
};
2011-01-12 22:05:45 +01:00
// Set the environ variable NODE_MODULE_CONTEXTS=1 to make node load all
// modules in thier own context.
Module._contextLoad = (+process.env['NODE_MODULE_CONTEXTS'] > 0);
Module._internalCache = {};
Module._cache = {};
Module._extensions = {};
Module._paths = [];
// Native modules don't need a full require function. So we can bootstrap
// most of the system with this mini-require.
Module._requireNative = function(id) {
if (id == 'module') {
return Module;
}
2011-01-12 22:05:45 +01:00
if (Module._internalCache[id]) {
return Module._internalCache[id].exports;
}
2011-01-12 22:05:45 +01:00
if (!natives[id]) {
throw new Error('No such native module ' + id);
}
2011-01-12 22:05:45 +01:00
var filename = id + '.js';
2011-01-12 22:05:45 +01:00
var fn = runInThisContext(Module.wrap(natives[id]), filename, true);
2011-01-12 22:05:45 +01:00
var m = {id: id, exports: {}};
fn(m.exports, Module._requireNative, m, filename);
m.loaded = true;
Module._internalCache[id] = m;
return m.exports;
};
Module.wrap = function(script) {
return Module.wrapper[0] + script + Module.wrapper[1];
};
2011-01-12 22:05:45 +01:00
Module.wrapper = [
'(function (exports, require, module, __filename, __dirname) { ',
'\n});'
];
var path = Module._requireNative('path');
Module._debug = function() {};
if (process.env.NODE_DEBUG && /module/.test(process.env.NODE_DEBUG)) {
Module._debug = function(x) {
console.error(x);
};
}
2011-01-12 22:05:45 +01:00
// We use this alias for the preprocessor that filters it out
var debug = Module._debug;
2010-12-02 12:11:23 -08:00
// given a module name, and a list of paths to test, returns the first
// matching file in the following precedence.
//
// require("a.<ext>")
// -> a.<ext>
//
// require("a")
// -> a
// -> a.<ext>
// -> a/index.<ext>
2011-01-12 22:05:45 +01:00
Module._findPath = function(request, paths) {
var fs = Module._requireNative('fs');
var exts = Object.keys(Module._extensions);
2011-01-12 22:05:45 +01:00
if (request.charAt(0) === '/') {
paths = [''];
}
// check if the file exists and is not a directory
2011-01-16 00:33:16 -08:00
function tryFile(requestPath) {
try {
2010-12-04 13:39:28 -08:00
var stats = fs.statSync(requestPath);
if (stats && !stats.isDirectory()) {
2011-01-04 12:24:17 -08:00
return fs.realpathSync(requestPath);
}
} catch (e) {}
return false;
};
// given a path check a the file exists with any of the set extensions
2011-01-16 00:33:16 -08:00
function tryExtensions(p, extension) {
for (var i = 0, EL = exts.length; i < EL; i++) {
f = tryFile(p + exts[i]);
if (f) { return f; }
}
return false;
};
// For each path
for (var i = 0, PL = paths.length; i < PL; i++) {
var p = paths[i],
// try to join the request to the path
f = tryFile(path.resolve(p, request)) ||
// try it with each of the extensions
tryExtensions(path.resolve(p, request)) ||
// try it with each of the extensions at "index"
tryExtensions(path.resolve(p, request, 'index'));
if (f) { return f; }
2010-12-02 12:11:23 -08:00
}
return false;
}
2011-01-12 22:05:45 +01:00
Module._resolveLookupPaths = function(request, parent) {
if (natives[request]) {
return [request, []];
}
2010-12-02 12:11:23 -08:00
var start = request.substring(0, 2);
if (start !== './' && start !== '..') {
2011-01-12 22:05:45 +01:00
return [request, Module._paths];
2010-12-02 12:11:23 -08:00
}
// with --eval, parent.id is not set and parent.filename is null
if (!parent || !parent.id || !parent.filename) {
// make require('./path/to/foo') work - normally the path is taken
// from realpath(__filename) but with eval there is no filename
2011-01-12 22:05:45 +01:00
return [request, ['.'].concat(Module._paths)];
2010-12-02 12:11:23 -08:00
}
// Is the parent an index module?
// We can assume the parent has a valid extension,
// as it already has been accepted as a module.
2011-01-12 22:05:45 +01:00
var isIndex = /^index\.\w+?$/.test(path.basename(parent.filename));
var parentIdPath = isIndex ? parent.id : path.dirname(parent.id);
var id = path.resolve(parentIdPath, request);
2010-12-02 12:11:23 -08:00
// make sure require('./path') and require('path') get distinct ids, even
// when called from the toplevel js file
if (parentIdPath === '.' && id.indexOf('/') === -1) {
id = './' + id;
}
2011-01-12 22:05:45 +01:00
2010-12-02 12:11:23 -08:00
debug('RELATIVE: requested:' + request +
' set ID to: ' + id + ' from ' + parent.id);
2011-01-12 22:05:45 +01:00
2010-12-02 12:11:23 -08:00
return [id, [path.dirname(parent.filename)]];
}
2011-01-12 22:05:45 +01:00
Module._load = function(request, parent) {
debug('Module._load REQUEST ' + (request) +
' parent: ' + parent.id);
2011-01-12 22:05:45 +01:00
var resolved = Module._resolveFilename(request, parent);
2010-12-02 12:11:23 -08:00
var id = resolved[0];
var filename = resolved[1];
2011-01-12 22:05:45 +01:00
var cachedModule = Module._cache[filename];
if (cachedModule) {
return cachedModule.exports;
}
2010-12-02 12:11:23 -08:00
// With natives id === request
// We deal with these first
if (natives[id]) {
// REPL is a special case, because it needs the real require.
if (id == 'repl') {
var replModule = new Module('repl');
replModule._compile(natives.repl, 'repl.js');
2011-01-12 22:05:45 +01:00
Module._internalCache.repl = replModule;
2010-12-02 12:11:23 -08:00
return replModule.exports;
}
debug('load native module ' + request);
2011-01-12 22:05:45 +01:00
return Module._requireNative(id);
}
2010-12-02 12:11:23 -08:00
var module = new Module(id, parent);
2011-01-12 22:05:45 +01:00
Module._cache[filename] = module;
2010-12-02 12:11:23 -08:00
module.load(filename);
return module.exports;
};
2011-01-12 22:05:45 +01:00
Module._resolveFilename = function(request, parent) {
if (natives[request]) {
return [request, request];
}
var resolvedModule = Module._resolveLookupPaths(request, parent);
var id = resolvedModule[0];
var paths = resolvedModule[1];
2010-12-02 12:11:23 -08:00
// look up the filename first, since that's the cache key.
debug('looking for ' + JSON.stringify(id) +
' in ' + JSON.stringify(paths));
2011-01-12 22:05:45 +01:00
var filename = Module._findPath(request, paths);
2010-12-02 12:11:23 -08:00
if (!filename) {
throw new Error("Cannot find module '" + request + "'");
}
2011-01-04 12:24:17 -08:00
id = filename;
2010-12-02 12:11:23 -08:00
return [id, filename];
}
2010-12-02 12:11:23 -08:00
Module.prototype.load = function(filename) {
debug('load ' + JSON.stringify(filename) +
' for module ' + JSON.stringify(this.id));
2010-12-02 12:11:23 -08:00
process.assert(!this.loaded);
this.filename = filename;
2010-12-02 12:11:23 -08:00
var extension = path.extname(filename) || '.js';
2011-01-12 22:05:45 +01:00
if (!Module._extensions[extension]) extension = '.js';
Module._extensions[extension](this, filename);
2010-12-02 12:11:23 -08:00
this.loaded = true;
};
2010-12-02 12:11:23 -08:00
// Returns exception if any
Module.prototype._compile = function(content, filename) {
var self = this;
// remove shebang
content = content.replace(/^\#\!.*/, '');
2010-12-02 12:11:23 -08:00
function require(path) {
2011-01-12 22:05:45 +01:00
return Module._load(path, self);
2010-12-02 12:11:23 -08:00
}
2010-12-02 12:11:23 -08:00
require.resolve = function(request) {
2011-01-12 22:05:45 +01:00
return Module._resolveFilename(request, self)[1];
}
2011-01-12 22:05:45 +01:00
require.paths = Module._paths;
2010-12-02 12:11:23 -08:00
require.main = process.mainModule;
// Enable support to add extra extension types
2011-01-12 22:05:45 +01:00
require.extensions = Module._extensions;
require.registerExtension = removed('require.registerExtension() ' +
'removed. Use require.extensions ' +
'instead.');
require.cache = Module._cache;
2010-12-02 12:11:23 -08:00
var dirname = path.dirname(filename);
2011-01-12 22:05:45 +01:00
if (Module._contextLoad) {
2010-12-02 12:11:23 -08:00
if (self.id !== '.') {
debug('load submodule');
// not root module
var sandbox = {};
for (var k in global) {
sandbox[k] = global[k];
}
sandbox.require = require;
sandbox.exports = self.exports;
sandbox.__filename = filename;
sandbox.__dirname = dirname;
sandbox.module = self;
sandbox.global = sandbox;
sandbox.root = root;
2011-01-01 21:14:24 -08:00
return runInNewContext(content, sandbox, filename, true);
2010-12-02 12:11:23 -08:00
}
2011-01-12 22:05:45 +01:00
debug('load root module');
// root module
global.require = require;
global.exports = self.exports;
global.__filename = filename;
global.__dirname = dirname;
global.module = self;
2010-12-02 12:11:23 -08:00
2011-01-12 22:05:45 +01:00
return runInThisContext(content, filename, true);
}
2011-01-12 22:05:45 +01:00
// create wrapper function
var wrapper = Module.wrap(content);
var compiledWrapper = runInThisContext(wrapper, filename, true);
if (filename === process.argv[1] && global.v8debug) {
global.v8debug.Debug.setBreakPoint(compiledWrapper, 0, 0);
}
var args = [self.exports, require, self, filename, dirname];
return compiledWrapper.apply(self.exports, args);
};
2010-12-02 12:11:23 -08:00
// Native extension for .js
2011-01-12 22:05:45 +01:00
Module._extensions['.js'] = function(module, filename) {
var content = Module._requireNative('fs').readFileSync(filename, 'utf8');
2010-12-02 12:11:23 -08:00
module._compile(content, filename);
};
2010-12-02 12:11:23 -08:00
// Native extension for .node
2011-01-12 22:05:45 +01:00
Module._extensions['.node'] = function(module, filename) {
2010-12-02 12:11:23 -08:00
process.dlopen(filename, module.exports);
};
2010-12-02 12:11:23 -08:00
// bootstrap main module.
2011-01-12 22:05:45 +01:00
Module.runMain = function() {
2010-12-02 12:11:23 -08:00
// Load the main module--the command line argument.
process.mainModule = new Module('.');
process.mainModule.load(process.argv[1]);
2010-12-02 12:11:23 -08:00
};
2011-01-12 22:05:45 +01:00
Module._initPaths = function() {
var paths = [path.resolve(process.execPath, '..', '..', 'lib', 'node')];
if (process.env['HOME']) {
paths.unshift(path.resolve(process.env['HOME'], '.node_libraries'));
paths.unshift(path.resolve(process.env['HOME'], '.node_modules'));
}
if (process.env['NODE_PATH']) {
paths = process.env['NODE_PATH'].split(':').concat(paths);
2011-01-12 22:05:45 +01:00
}
Module._paths = paths;
};
2010-12-02 12:11:23 -08:00
// bootstrap repl
2011-01-12 22:05:45 +01:00
Module.requireRepl = function() {
return Module._load('repl', '.');
};
Module._initPaths();
2011-01-12 22:05:45 +01:00
// backwards compatibility
Module.Module = Module;
2011-01-12 22:05:45 +01:00
return Module;
2010-12-02 12:11:23 -08:00
})();
2010-12-02 12:11:23 -08:00
// Load events module in order to access prototype elements on process like
// process.addListener.
2011-01-12 22:05:45 +01:00
var events = Module._requireNative('events');
2010-12-02 12:11:23 -08:00
// Signal Handlers
(function() {
var signalWatchers = {};
var addListener = process.addListener;
var removeListener = process.removeListener;
2010-12-02 12:11:23 -08:00
function isSignal(event) {
return event.slice(0, 3) === 'SIG' && lazyConstants()[event];
}
2010-12-02 12:11:23 -08:00
// Wrap addListener for the special signal types
process.on = process.addListener = function(type, listener) {
var ret = addListener.apply(this, arguments);
if (isSignal(type)) {
if (!signalWatchers.hasOwnProperty(type)) {
var b = process.binding('signal_watcher');
var w = new b.SignalWatcher(lazyConstants()[type]);
w.callback = function() { process.emit(type); };
signalWatchers[type] = w;
w.start();
} else if (this.listeners(type).length === 1) {
signalWatchers[event].start();
}
}
return ret;
};
2010-12-02 12:11:23 -08:00
process.removeListener = function(type, listener) {
var ret = removeListener.apply(this, arguments);
if (isSignal(type)) {
process.assert(signalWatchers.hasOwnProperty(type));
2010-12-02 12:11:23 -08:00
if (this.listeners(type).length === 0) {
signalWatchers[type].stop();
}
}
2010-12-02 12:11:23 -08:00
return ret;
};
})();
2010-12-02 12:11:23 -08:00
global.setTimeout = function() {
2011-01-12 22:05:45 +01:00
var t = Module._requireNative('timers');
2010-12-02 12:11:23 -08:00
return t.setTimeout.apply(this, arguments);
};
2010-12-02 12:11:23 -08:00
global.setInterval = function() {
2011-01-12 22:05:45 +01:00
var t = Module._requireNative('timers');
2010-12-02 12:11:23 -08:00
return t.setInterval.apply(this, arguments);
};
2010-12-02 12:11:23 -08:00
global.clearTimeout = function() {
2011-01-12 22:05:45 +01:00
var t = Module._requireNative('timers');
2010-12-02 12:11:23 -08:00
return t.clearTimeout.apply(this, arguments);
};
2010-12-02 12:11:23 -08:00
global.clearInterval = function() {
2011-01-12 22:05:45 +01:00
var t = Module._requireNative('timers');
2010-12-02 12:11:23 -08:00
return t.clearInterval.apply(this, arguments);
};
2011-01-01 21:54:46 -08:00
var stdout, stdin;
2010-12-02 12:11:23 -08:00
process.__defineGetter__('stdout', function() {
if (stdout) return stdout;
2010-12-02 12:11:23 -08:00
var binding = process.binding('stdio'),
2011-01-12 22:05:45 +01:00
net = Module._requireNative('net'),
fs = Module._requireNative('fs'),
2010-12-02 12:11:23 -08:00
fd = binding.stdoutFD;
2010-12-02 12:11:23 -08:00
if (binding.isStdoutBlocking()) {
stdout = new fs.WriteStream(null, {fd: fd});
} else {
stdout = new net.Stream(fd);
// FIXME Should probably have an option in net.Stream to create a
// stream from an existing fd which is writable only. But for now
// we'll just add this hack and set the `readable` member to false.
// Test: ./node test/fixtures/echo.js < /etc/passwd
stdout.readable = false;
}
2010-12-02 12:11:23 -08:00
return stdout;
});
2011-01-01 21:54:46 -08:00
process.__defineGetter__('stdin', function() {
2010-12-02 12:11:23 -08:00
if (stdin) return stdin;
2010-12-02 12:11:23 -08:00
var binding = process.binding('stdio'),
2011-01-12 22:05:45 +01:00
net = Module._requireNative('net'),
fs = Module._requireNative('fs'),
2010-12-02 12:11:23 -08:00
fd = binding.openStdin();
2010-12-02 12:11:23 -08:00
if (binding.isStdinBlocking()) {
stdin = new fs.ReadStream(null, {fd: fd});
} else {
stdin = new net.Stream(fd);
stdin.readable = true;
}
2010-12-02 12:11:23 -08:00
return stdin;
2011-01-01 21:54:46 -08:00
});
process.openStdin = function() {
process.stdin.resume();
return process.stdin;
2010-12-02 12:11:23 -08:00
};
2010-12-02 12:11:23 -08:00
// Lazy load console object
global.__defineGetter__('console', function() {
2011-01-12 22:05:45 +01:00
return Module._requireNative('console');
2010-12-02 12:11:23 -08:00
});
2011-01-12 22:05:45 +01:00
global.Buffer = Module._requireNative('buffer').Buffer;
2010-12-02 12:11:23 -08:00
process.exit = function(code) {
process.emit('exit', code || 0);
process.reallyExit(code || 0);
};
2010-12-02 12:11:23 -08:00
process.kill = function(pid, sig) {
sig = sig || 'SIGTERM';
if (!lazyConstants()[sig]) throw new Error('Unknown signal: ' + sig);
process._kill(pid, lazyConstants()[sig]);
};
2010-12-02 12:11:23 -08:00
var cwd = process.cwd();
2011-01-12 22:05:45 +01:00
var path = Module._requireNative('path');
var isWindows = process.platform === 'win32';
// Make process.argv[0] and process.argv[1] into full paths, but only
// touch argv[0] if it's not a system $PATH lookup.
// TODO: Make this work on Windows as well. Note that "node" might
// execute cwd\node.exe, or some %PATH%\node.exe on Windows,
// and that every directory has its own cwd, so d:node.exe is valid.
var argv0 = process.argv[0];
if (!isWindows && argv0.indexOf('/') !== -1 && argv0.charAt(0) !== '/') {
2010-12-02 12:11:23 -08:00
process.argv[0] = path.join(cwd, process.argv[0]);
}
2010-06-07 16:15:41 -07:00
// To allow people to extend Node in different ways, this hook allows
// one to drop a file lib/_third_party_main.js into the build directory
// which will be executed instead of Node's normal loading.
if (process.binding('natives')['_third_party_main']) {
process.nextTick(function () {
Module._requireNative('_third_party_main');
});
return;
}
2010-12-02 12:11:23 -08:00
if (process.argv[1]) {
if (process.argv[1] == 'debug') {
// Start the debugger agent
2011-01-12 22:05:45 +01:00
var d = Module._requireNative('_debugger');
d.start();
2011-01-12 22:05:45 +01:00
return;
}
2011-01-12 22:05:45 +01:00
// Load Module
// make process.argv[1] into a full path
if (!(/^http:\/\//).exec(process.argv[1])) {
process.argv[1] = path.resolve(process.argv[1]);
2010-12-02 12:11:23 -08:00
}
2011-01-12 22:05:45 +01:00
// REMOVEME: nextTick should not be necessary. This hack to get
// test/simple/test-exception-handler2.js working.
process.nextTick(Module.runMain);
return;
}
2010-12-02 12:11:23 -08:00
2011-01-12 22:05:45 +01:00
if (process._eval) {
2010-12-02 12:11:23 -08:00
// -e, --eval
2011-01-12 22:05:45 +01:00
var rv = new Module()._compile('return eval(process._eval)', 'eval');
2010-12-02 12:11:23 -08:00
console.log(rv);
2011-01-12 22:05:45 +01:00
return;
2010-06-07 16:15:41 -07:00
}
2011-01-12 22:05:45 +01:00
// REPL
Module.requireRepl().start();
2010-03-11 22:05:09 -08:00
});