3 process.global.process = process;
4 process.global.global = process.global;
5 global.GLOBAL = global;
7 /** deprecation errors ************************************************/
9 function removed (reason) {
11 throw new Error(reason)
15 GLOBAL.__module = removed("'__module' has been renamed to 'module'");
16 GLOBAL.include = removed("include(module) has been removed. Use require(module)");
17 GLOBAL.puts = removed("puts() has moved. Use require('sys') to bring it back.");
18 GLOBAL.print = removed("print() has moved. Use require('sys') to bring it back.");
19 GLOBAL.p = removed("p() has moved. Use require('sys') to bring it back.");
20 process.debug = removed("process.debug() has moved. Use require('sys') to bring it back.");
21 process.error = removed("process.error() has moved. Use require('sys') to bring it back.");
22 process.watchFile = removed("process.watchFile() has moved to fs.watchFile()");
23 process.unwatchFile = removed("process.unwatchFile() has moved to fs.unwatchFile()");
24 process.mixin = removed('process.mixin() has been removed.');
28 node.createProcess = removed("node.createProcess() has been changed to process.createChildProcess() update your code");
29 process.createChildProcess = removed("childProcess API has changed. See doc/api.txt.");
30 node.exec = removed("process.exec() has moved. Use require('sys') to bring it back.");
31 node.inherits = removed("node.inherits() has moved. Use require('sys') to access it.");
32 process.inherits = removed("process.inherits() has moved to sys.inherits.");
35 node.http.createServer = removed("node.http.createServer() has moved. Use require('http') to access it.");
36 node.http.createClient = removed("node.http.createClient() has moved. Use require('http') to access it.");
39 node.tcp.createServer = removed("node.tcp.createServer() has moved. Use require('tcp') to access it.");
40 node.tcp.createConnection = removed("node.tcp.createConnection() has moved. Use require('tcp') to access it.");
43 node.dns.createConnection = removed("node.dns.createConnection() has moved. Use require('dns') to access it.");
45 /**********************************************************************/
49 var internalModuleCache = {};
50 var extensionCache = {};
52 function Module (id, parent) {
58 this.moduleCache = parent.moduleCache;
60 this.moduleCache = {};
62 this.moduleCache[this.id] = this;
70 function createInternalModule (id, constructor) {
71 var m = new Module(id);
72 constructor(m.exports);
74 internalModuleCache[id] = m;
79 // This contains the source code for the files in lib/
80 // Like, natives.fs is the contents of lib/fs.js
81 var natives = process.binding('natives');
83 function loadNative (id) {
84 var m = new Module(id);
85 internalModuleCache[id] = m;
86 var e = m._compile(natives[id], id);
92 function requireNative (id) {
93 if (internalModuleCache[id]) return internalModuleCache[id].exports;
94 if (!natives[id]) throw new Error('No such native module ' + id);
95 return loadNative(id).exports;
99 process.assert = function (x, msg) {
100 if (!(x)) throw new Error(msg || "assertion error");
103 process.evalcx = process.binding('evals').Script.runInNewContext;
106 var eventsModule = createInternalModule
109 ( "(function (exports) {" + natives.events + "})"
113 var events = eventsModule.exports;
117 var nextTickQueue = [];
119 process._tickCallback = function () {
120 var l = nextTickQueue.length;
122 var cb = nextTickQueue.shift();
127 process.nextTick = function (callback) {
128 nextTickQueue.push(callback);
129 process._needTickCallback();
138 function isSignal (event) {
139 return event.slice(0, 3) === 'SIG' && process.hasOwnProperty(event);
142 process.addListener("newListener", function (event) {
143 if (isSignal(event) && process.listeners(event).length === 0) {
144 var b = process.binding('signal_watcher');
145 var w = new b.SignalWatcher(process[event]);
146 w.addListener("signal", function () {
154 function addTimerListener (callback) {
156 // Special case the no param case to avoid the extra object creation.
157 if (arguments.length > 2) {
158 var args = Array.prototype.slice.call(arguments, 2);
159 timer.callback = function () { callback.apply(timer, args); };
161 timer.callback = callback;
165 global.setTimeout = function (callback, after) {
166 var timer = new process.Timer();
167 addTimerListener.apply(timer, arguments);
168 timer.start(after, 0);
172 global.setInterval = function (callback, repeat) {
173 var timer = new process.Timer();
174 addTimerListener.apply(timer, arguments);
175 timer.start(repeat, repeat);
179 global.clearTimeout = function (timer) {
180 if (timer instanceof process.Timer) {
185 global.clearInterval = global.clearTimeout;
192 var debugLevel = parseInt(process.env["NODE_DEBUG"]);
194 if (debugLevel > 0) {
195 process.binding('stdio').writeError(x + "\n");
199 var pathModule = createInternalModule
202 ( "(function (exports) {" + natives.path + "})"
207 var path = pathModule.exports;
209 function existsSync (path) {
211 process.binding('fs').stat(path);
220 var modulePaths = [];
222 if (process.env["HOME"]) {
223 modulePaths.unshift(path.join(process.env["HOME"], ".node_libraries"));
226 if (process.env["NODE_PATH"]) {
227 modulePaths = process.env["NODE_PATH"].split(":").concat(modulePaths);
231 /* Sync unless callback given */
232 function findModulePath (id, dirs, callback) {
233 process.assert(dirs.constructor == Array);
235 if (/^https?:\/\//.exec(id)) {
239 throw new Error("Sync http require not allowed.");
244 if (/\.(js|node)$/.exec(id)) {
245 throw new Error("No longer accepting filename extension in module names");
248 if (dirs.length == 0) {
252 return; // sync returns null
257 var rest = dirs.slice(1, dirs.length);
259 if (id.charAt(0) == '/') {
265 path.join(dir, id + ".js"),
266 path.join(dir, id + ".node"),
267 path.join(dir, id, "index.js"),
268 path.join(dir, id, "index.node")
272 var extensions = Object.keys(extensionCache);
273 for (var i = 0, l = extensions.length; i < l; i++) {
274 var ext = extensions[i];
275 locations.push(path.join(dir, id + ext));
276 locations.push(path.join(dir, id, 'index' + ext));
279 function searchLocations () {
280 var location = locations.shift();
282 return findModulePath(id, rest, callback);
287 path.exists(location, function (found) {
291 return searchLocations();
297 if (existsSync(location)) {
300 return searchLocations();
304 return searchLocations();
308 // sync - no i/o performed
309 function resolveModulePath(request, parent) {
311 if (request.charAt(0) == "." && (request.charAt(1) == "/" || request.charAt(1) == ".")) {
313 debug("RELATIVE: requested:" + request + " set ID to: "+id+" from "+parent.id);
315 var exts = ['js', 'node'], ext;
316 var extensions = Object.keys(extensionCache);
317 for (var i = 0, l = extensions.length; i < l; i++) {
318 var ext = extensions[i];
319 exts.push(ext.slice(1));
322 var parentIdPath = path.dirname(parent.id +
323 (path.basename(parent.filename).match(new RegExp('^index\\.(' + exts.join('|') + ')$')) ? "/" : ""));
324 id = path.join(parentIdPath, request);
325 paths = [path.dirname(parent.filename)];
328 // debug("ABSOLUTE: id="+id);
336 function loadModule (request, parent, callback) {
337 var resolvedModule = resolveModulePath(request, parent),
338 id = resolvedModule[0],
339 paths = resolvedModule[1];
341 debug("loadModule REQUEST " + (request) + " parent: " + parent.id);
343 var cachedModule = internalModuleCache[id] || parent.moduleCache[id];
346 // Try to compile from native modules
348 debug('load native module ' + id);
349 cachedModule = loadNative(id);
354 debug("found " + JSON.stringify(id) + " in cache");
356 callback(null, cachedModule.exports);
358 return cachedModule.exports;
363 debug("looking for " + JSON.stringify(id) + " in " + JSON.stringify(paths));
367 var filename = findModulePath(request, paths);
369 throw new Error("Cannot find module '" + request + "'");
371 var module = new Module(id, parent);
372 module.loadSync(filename);
373 return module.exports;
378 findModulePath(request, paths, function (filename) {
380 var err = new Error("Cannot find module '" + request + "'");
383 var module = new Module(id, parent);
384 module.load(filename, callback);
392 // This function allows the user to register file extensions to custom
393 // Javascript 'compilers'. It accepts 2 arguments, where ext is a file
394 // extension as a string. E.g. '.coffee' for coffee-script files. compiler
395 // is the second argument, which is a function that gets called when the
396 // specified file extension is found. The compiler is passed a single
397 // argument, which is, the file contents, which need to be compiled.
399 // The function needs to return the compiled source, or an non-string
400 // variable that will get attached directly to the module exports. Example:
402 // require.registerExtension('.coffee', function(content) {
403 // return doCompileMagic(content);
405 function registerExtension(ext, compiler) {
406 if ('string' !== typeof ext && false === /\.\w+$/.test(ext)) {
407 throw new Error('require.registerExtension: First argument not a valid extension string.');
410 if ('function' !== typeof compiler) {
411 throw new Error('require.registerExtension: Second argument not a valid compiler function.');
414 extensionCache[ext] = compiler;
418 Module.prototype.loadSync = function (filename) {
419 debug("loadSync " + JSON.stringify(filename) + " for module " + JSON.stringify(this.id));
421 process.assert(!this.loaded);
422 this.filename = filename;
424 if (filename.match(/\.node$/)) {
425 this._loadObjectSync(filename);
427 this._loadScriptSync(filename);
432 Module.prototype.load = function (filename, callback) {
433 debug("load " + JSON.stringify(filename) + " for module " + JSON.stringify(this.id));
435 process.assert(!this.loaded);
437 this.filename = filename;
439 if (filename.match(/\.node$/)) {
440 this._loadObject(filename, callback);
442 this._loadScript(filename, callback);
447 Module.prototype._loadObjectSync = function (filename) {
449 process.dlopen(filename, this.exports);
453 Module.prototype._loadObject = function (filename, callback) {
455 // XXX Not yet supporting loading from HTTP. would need to download the
456 // file, store it to tmp then run dlopen on it.
458 process.dlopen(filename, self.exports); // FIXME synchronus
459 if (callback) callback(null, self.exports);
463 function cat (id, callback) {
464 if (id.match(/^http:\/\//)) {
465 loadModule('http', process.mainModule, function (err, http) {
467 if (callback) callback(err);
469 http.cat(id, callback);
473 requireNative('fs').readFile(id, callback);
478 // Returns exception if any
479 Module.prototype._compile = function (content, filename) {
482 content = content.replace(/^\#\!.*/, '');
484 // Compile content if needed
485 var ext = path.extname(filename);
486 if (extensionCache[ext]) {
487 content = extensionCache[ext](content);
490 function requireAsync (url, cb) {
491 loadModule(url, self, cb);
494 function require (path) {
495 return loadModule(path, self);
498 require.paths = modulePaths;
499 require.async = requireAsync;
500 require.main = process.mainModule;
501 require.registerExtension = registerExtension;
504 if ('string' === typeof content) {
505 // create wrapper function
506 var wrapper = "(function (exports, require, module, __filename, __dirname) { "
511 var compiledWrapper = process.compile(wrapper, filename);
512 var dirName = path.dirname(filename);
513 if (filename === process.argv[1]) {
514 process.checkBreak();
516 compiledWrapper.apply(self.exports, [self.exports, require, self, filename, dirName]);
521 self.exports = content;
526 Module.prototype._loadScriptSync = function (filename) {
527 var content = requireNative('fs').readFileSync(filename);
528 var e = this._compile(content, filename);
537 Module.prototype._loadScript = function (filename, callback) {
539 cat(filename, function (err, content) {
542 if (callback) callback(err);
544 var e = self._compile(content, filename);
546 if (callback) callback(e);
548 self._waitChildrenLoad(function () {
550 if (self.onload) self.onload();
551 if (callback) callback(null, self.exports);
559 Module.prototype._waitChildrenLoad = function (callback) {
561 var children = this.children;
562 for (var i = 0; i < children.length; i++) {
563 var child = children[i];
567 child.onload = function () {
570 if (children.length == nloaded && callback) callback();
574 if (children.length == nloaded && callback) callback();
579 process.__defineGetter__('stdout', function () {
580 if (stdout) return stdout;
581 var net = requireNative('net');
582 stdout = new net.Stream(process.binding('stdio').stdoutFD);
587 process.openStdin = function () {
588 if (stdin) return stdin;
589 var net = requireNative('net');
590 var fd = process.binding('stdio').openStdin();
591 stdin = new net.Stream(fd);
593 stdin.readable = true;
598 process.exit = function (code) {
599 process.emit("exit");
600 process.reallyExit(code);
603 var cwd = process.cwd();
605 // Make process.argv[0] and process.argv[1] into full paths.
606 if (process.argv[0].indexOf('/') > 0) {
607 process.argv[0] = path.join(cwd, process.argv[0]);
610 if (process.argv[1].charAt(0) != "/" && !(/^http:\/\//).exec(process.argv[1])) {
611 process.argv[1] = path.join(cwd, process.argv[1]);
614 // Load the main module--the command line argument.
615 process.mainModule = new Module(".");
616 process.mainModule.load(process.argv[1], function (err) {
620 // All our arguments are loaded. We've evaluated all of the scripts. We
621 // might even have created TCP servers. Now we enter the main eventloop. If
622 // there are no watchers on the loop (except for the ones that were
623 // ev_unref'd) then this function exits. As long as there are active
624 // watchers, it blocks.
627 process.emit("exit");