You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

628 lines
20 KiB

// Hello, and welcome to hacking node.js!
//
// This file is invoked by node::LoadEnvironment in src/node.cc, and is
// responsible for bootstrapping the node.js core. As special caution is given
// to the performance of the startup process, many dependencies are invoked
// lazily.
'use strict';
(function(process) {
function startup() {
const EventEmitter = NativeModule.require('events');
process._eventsCount = 0;
const origProcProto = Object.getPrototypeOf(process);
Object.setPrototypeOf(origProcProto, EventEmitter.prototype);
EventEmitter.call(process);
setupProcessObject();
// do this good and early, since it handles errors.
setupProcessFatal();
setupProcessICUVersions();
setupGlobalVariables();
const browserGlobals = !process._noBrowserGlobals;
if (browserGlobals) {
setupGlobalTimeouts();
setupGlobalConsole();
}
const _process = NativeModule.require('internal/process');
const perf = process.binding('performance');
const {
NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE,
NODE_PERFORMANCE_MILESTONE_THIRD_PARTY_MAIN_START,
NODE_PERFORMANCE_MILESTONE_THIRD_PARTY_MAIN_END,
NODE_PERFORMANCE_MILESTONE_CLUSTER_SETUP_START,
NODE_PERFORMANCE_MILESTONE_CLUSTER_SETUP_END,
NODE_PERFORMANCE_MILESTONE_MODULE_LOAD_START,
NODE_PERFORMANCE_MILESTONE_MODULE_LOAD_END,
NODE_PERFORMANCE_MILESTONE_PRELOAD_MODULE_LOAD_START,
NODE_PERFORMANCE_MILESTONE_PRELOAD_MODULE_LOAD_END
} = perf.constants;
_process.setup_hrtime();
_process.setup_performance();
_process.setup_cpuUsage();
_process.setupMemoryUsage();
_process.setupConfig(NativeModule._source);
process: add 'warning' event and process.emitWarning() In several places throughout the code we write directly to stderr to report warnings (deprecation, possible eventemitter memory leak). The current design of simply dumping the text to stderr is less than ideal. This PR introduces a new "process warnings" mechanism that emits 'warning' events on the global process object. These are invoked with a `warning` argument whose value is an Error object. By default, these warnings will be printed to stderr. This can be suppressed using the `--no-warnings` and `--no-deprecation` command line flags. For warnings, the 'warning' event will still be emitted by the process, allowing applications to handle the warnings in custom ways. The existing `--no-deprecation` flag will continue to supress all deprecation output generated by the core lib. The `--trace-warnings` command line flag will tell Node.js to print the full stack trace of warnings as part of the default handling. The existing `--no-deprecation`, `--throw-deprecation` and `--trace-deprecation` flags continue to work as they currently do, but the exact output of the warning message is modified to occur on process.nextTick(). The stack trace for the warnings and deprecations preserve and point to the correct call site. A new `process.emitWarning()` API is provided to permit userland to emit warnings and deprecations using the same consistent mechanism. Test cases and documentation are included. PR-URL: https://github.com/nodejs/node/pull/4782 Reviewed-By: Rod Vagg <rod@vagg.org> Reviewed-By: Wyatt Preul <wpreul@gmail.com> Reviewed-By: Jeremiah Senkpiel <fishrock123@rocketmail.com>
9 years ago
NativeModule.require('internal/process/warning').setup();
NativeModule.require('internal/process/next_tick').setup();
NativeModule.require('internal/process/stdio').setup();
if (browserGlobals) {
// Instantiate eagerly in case the first call is under stack overflow
// conditions where instantiation doesn't work.
const console = global.console;
console.assert;
console.clear;
console.count;
console.countReset;
console.dir;
console.error;
console.log;
console.time;
console.timeEnd;
console.trace;
console.warn;
}
_process.setupKillAndExit();
_process.setupSignalHandlers();
if (global.__coverage__)
NativeModule.require('internal/process/write-coverage').setup();
inspector: enable async stack traces Implement a special async_hooks listener that forwards information about async tasks to V8Inspector asyncTask* API, thus enabling DevTools feature "async stack traces". The feature is enabled only on 64bit platforms due to a technical limitation of V8 Inspector: inspector uses a pointer as a task id, while async_hooks use 64bit numbers as ids. To avoid performance penalty of async_hooks when not debugging, the new listener is enabled only when the process enters a debug mode: - When the process is started with `--inspect` or `--inspect-brk`, the listener is enabled immediately and async stack traces lead all the way to the first tick of the event loop. - When the debug mode is enabled via SIGUSR1 or `_debugProcess()`, the listener is enabled together with the debugger. As a result, only async operations started after the signal was received will be correctly observed and reported to V8 Inspector. For example, a `setInterval()` called in the first tick of the event will not be shown in the async stack trace when the callback is invoked. This behaviour is consistent with Chrome DevTools. Last but not least, this commit fixes handling of InspectorAgent's internal property `enabled_` to ensure it's set back to `false` after the debugger is deactivated (typically via `process._debugEnd()`). Fixes: https://github.com/nodejs/node/issues/11370 PR-URL: https://github.com/nodejs/node/pull/13870 Reviewed-by: Timothy Gu <timothygu99@gmail.com> Reviewed-by: Anna Henningsen <anna@addaleax.net>
8 years ago
NativeModule.require('internal/inspector_async_hook').setup();
// Do not initialize channel in debugger agent, it deletes env variable
// and the main thread won't see it.
if (process.argv[1] !== '--debug-agent')
_process.setupChannel();
_process.setupRawDebug();
// Ensure setURLConstructor() is called before the native
// URL::ToObject() method is used.
NativeModule.require('internal/url');
Object.defineProperty(process, 'argv0', {
enumerable: true,
configurable: false,
value: process.argv[0]
});
process.argv[0] = process.execPath;
// Handle `--debug*` deprecation and invalidation
if (process._invalidDebug) {
process.emitWarning(
'`node --debug` and `node --debug-brk` are invalid. ' +
'Please use `node --inspect` or `node --inspect-brk` instead.',
'DeprecationWarning', 'DEP0062', startup, true);
process.exit(9);
} else if (process._deprecatedDebugBrk) {
process.emitWarning(
'`node --inspect --debug-brk` is deprecated. ' +
'Please use `node --inspect-brk` instead.',
'DeprecationWarning', 'DEP0062', startup, true);
}
if (process.binding('config').experimentalModules) {
process.emitWarning(
'The ESM module loader is experimental.',
'ExperimentalWarning', undefined);
}
// There are various modes that Node can run in. The most common two
// are running from a script and running the REPL - but there are a few
// others like the debugger or running --eval arguments. Here we decide
// which mode we run in.
if (NativeModule.exists('_third_party_main')) {
// 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.
process.nextTick(function() {
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_THIRD_PARTY_MAIN_START);
NativeModule.require('_third_party_main');
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_THIRD_PARTY_MAIN_END);
});
} else if (process.argv[1] === 'inspect' || process.argv[1] === 'debug') {
if (process.argv[1] === 'debug') {
process.emitWarning(
'`node debug` is deprecated. Please use `node inspect` instead.',
'DeprecationWarning', 'DEP0068');
}
// Start the debugger agent
process.nextTick(function() {
NativeModule.require('node-inspect/lib/_inspect').start();
});
} else if (process.profProcess) {
NativeModule.require('internal/v8_prof_processor');
} else {
// There is user code to be run
// If this is a worker in cluster mode, start up the communication
// channel. This needs to be done before any user code gets executed
// (including preload modules).
if (process.argv[1] && process.env.NODE_UNIQUE_ID) {
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_CLUSTER_SETUP_START);
const cluster = NativeModule.require('cluster');
cluster._setupWorker();
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_CLUSTER_SETUP_END);
// Make sure it's not accidentally inherited by child processes.
delete process.env.NODE_UNIQUE_ID;
}
if (process._eval != null && !process._forceRepl) {
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_MODULE_LOAD_START);
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_MODULE_LOAD_END);
// User passed '-e' or '--eval' arguments to Node without '-i' or
// '--interactive'
perf.markMilestone(
NODE_PERFORMANCE_MILESTONE_PRELOAD_MODULE_LOAD_START);
preloadModules();
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_PRELOAD_MODULE_LOAD_END);
const internalModule = NativeModule.require('internal/module');
internalModule.addBuiltinLibsToObject(global);
evalScript('[eval]');
} else if (process.argv[1] && process.argv[1] !== '-') {
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_MODULE_LOAD_START);
// make process.argv[1] into a full path
const path = NativeModule.require('path');
process.argv[1] = path.resolve(process.argv[1]);
const Module = NativeModule.require('module');
// check if user passed `-c` or `--check` arguments to Node.
if (process._syntax_check_only != null) {
const fs = NativeModule.require('fs');
// read the source
const filename = Module._resolveFilename(process.argv[1]);
var source = fs.readFileSync(filename, 'utf-8');
checkScriptSyntax(source, filename);
process.exit(0);
}
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_MODULE_LOAD_END);
perf.markMilestone(
NODE_PERFORMANCE_MILESTONE_PRELOAD_MODULE_LOAD_START);
preloadModules();
perf.markMilestone(
NODE_PERFORMANCE_MILESTONE_PRELOAD_MODULE_LOAD_END);
Module.runMain();
} else {
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_MODULE_LOAD_START);
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_MODULE_LOAD_END);
perf.markMilestone(
NODE_PERFORMANCE_MILESTONE_PRELOAD_MODULE_LOAD_START);
preloadModules();
perf.markMilestone(
NODE_PERFORMANCE_MILESTONE_PRELOAD_MODULE_LOAD_END);
// If -i or --interactive were passed, or stdin is a TTY.
if (process._forceRepl || NativeModule.require('tty').isatty(0)) {
// REPL
const cliRepl = NativeModule.require('internal/repl');
cliRepl.createInternalRepl(process.env, function(err, repl) {
if (err) {
throw err;
}
repl.on('exit', function() {
if (repl._flushing) {
repl.pause();
return repl.once('flushHistory', function() {
process.exit();
});
}
process.exit();
});
});
if (process._eval != null) {
// User passed '-e' or '--eval'
evalScript('[eval]');
}
} else {
// Read all of stdin - execute it.
process.stdin.setEncoding('utf8');
var code = '';
process.stdin.on('data', function(d) {
code += d;
});
process.stdin.on('end', function() {
if (process._syntax_check_only != null) {
checkScriptSyntax(code, '[stdin]');
} else {
process._eval = code;
evalScript('[stdin]');
}
});
}
}
}
perf.markMilestone(NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE);
}
function setupProcessObject() {
process._setupProcessObject(pushValueToArray);
function pushValueToArray() {
for (var i = 0; i < arguments.length; i++)
this.push(arguments[i]);
}
}
function setupGlobalVariables() {
Object.defineProperty(global, Symbol.toStringTag, {
value: 'global',
writable: false,
enumerable: false,
configurable: true
});
global.process = process;
const util = NativeModule.require('util');
function makeGetter(name) {
return util.deprecate(function() {
return this;
}, `'${name}' is deprecated, use 'global'`, 'DEP0016');
}
function makeSetter(name) {
return util.deprecate(function(value) {
Object.defineProperty(this, name, {
configurable: true,
writable: true,
enumerable: true,
value: value
});
}, `'${name}' is deprecated, use 'global'`, 'DEP0016');
}
Object.defineProperties(global, {
GLOBAL: {
configurable: true,
get: makeGetter('GLOBAL'),
set: makeSetter('GLOBAL')
},
root: {
configurable: true,
get: makeGetter('root'),
set: makeSetter('root')
}
});
global.Buffer = NativeModule.require('buffer').Buffer;
process.domain = null;
process._exiting = false;
}
function setupGlobalTimeouts() {
const timers = NativeModule.require('timers');
global.clearImmediate = timers.clearImmediate;
global.clearInterval = timers.clearInterval;
global.clearTimeout = timers.clearTimeout;
global.setImmediate = timers.setImmediate;
global.setInterval = timers.setInterval;
global.setTimeout = timers.setTimeout;
}
function setupGlobalConsole() {
const originalConsole = global.console;
let console;
Object.defineProperty(global, 'console', {
configurable: true,
enumerable: true,
get: function() {
if (!console) {
console = (originalConsole === undefined) ?
NativeModule.require('console') :
installInspectorConsole(originalConsole);
}
return console;
}
});
setupInspectorCommandLineAPI();
}
function installInspectorConsole(globalConsole) {
const wrappedConsole = NativeModule.require('console');
const inspector = process.binding('inspector');
if (!inspector.consoleCall) {
return wrappedConsole;
}
const config = {};
for (const key of Object.keys(wrappedConsole)) {
if (!globalConsole.hasOwnProperty(key))
continue;
// If global console has the same method as inspector console,
// then wrap these two methods into one. Native wrapper will preserve
// the original stack.
wrappedConsole[key] = inspector.consoleCall.bind(wrappedConsole,
globalConsole[key],
wrappedConsole[key],
config);
}
for (const key of Object.keys(globalConsole)) {
if (wrappedConsole.hasOwnProperty(key))
continue;
wrappedConsole[key] = globalConsole[key];
}
return wrappedConsole;
}
function setupInspectorCommandLineAPI() {
const { addCommandLineAPI } = process.binding('inspector');
if (!addCommandLineAPI) return;
const Module = NativeModule.require('module');
const { makeRequireFunction } = NativeModule.require('internal/module');
const path = NativeModule.require('path');
const cwd = tryGetCwd(path);
const consoleAPIModule = new Module('<inspector console>');
consoleAPIModule.paths =
Module._nodeModulePaths(cwd).concat(Module.globalPaths);
addCommandLineAPI('require', makeRequireFunction(consoleAPIModule));
}
function setupProcessFatal() {
const async_wrap = process.binding('async_wrap');
// Arrays containing hook flags and ids for async_hook calls.
const { async_hook_fields, async_uid_fields } = async_wrap;
// Internal functions needed to manipulate the stack.
const { clearIdStack, asyncIdStackSize } = async_wrap;
const { kAfter, kCurrentAsyncId, kInitTriggerId } = async_wrap.constants;
process._fatalException = function(er) {
var caught;
// It's possible that kInitTriggerId was set for a constructor call that
// threw and was never cleared. So clear it now.
async_uid_fields[kInitTriggerId] = 0;
if (process.domain && process.domain._errorHandler)
caught = process.domain._errorHandler(er);
if (!caught)
caught = process.emit('uncaughtException', er);
// If someone handled it, then great. otherwise, die in C++ land
// since that means that we'll exit the process, emit the 'exit' event
if (!caught) {
try {
if (!process._exiting) {
process._exiting = true;
process.emit('exit', 1);
}
} catch (er) {
// nothing to be done about it at this point.
}
} else {
// If we handled an error, then make sure any ticks get processed
NativeModule.require('timers').setImmediate(process._tickCallback);
// Emit the after() hooks now that the exception has been handled.
if (async_hook_fields[kAfter] > 0) {
do {
NativeModule.require('async_hooks').emitAfter(
async_uid_fields[kCurrentAsyncId]);
} while (asyncIdStackSize() > 0);
// Or completely empty the id stack.
} else {
clearIdStack();
}
}
return caught;
};
}
function setupProcessICUVersions() {
const icu = process.binding('config').hasIntl ?
process.binding('icu') : undefined;
if (!icu) return; // no Intl/ICU: nothing to add here.
// With no argument, getVersion() returns a comma separated list
// of possible types.
const versionTypes = icu.getVersion().split(',');
for (var n = 0; n < versionTypes.length; n++) {
var name = versionTypes[n];
const version = icu.getVersion(name);
Object.defineProperty(process.versions, name, {
writable: false,
enumerable: true,
value: version
});
}
}
function tryGetCwd(path) {
try {
return process.cwd();
} catch (ex) {
// getcwd(3) can fail if the current working directory has been deleted.
// Fall back to the directory name of the (absolute) executable path.
// It's not really correct but what are the alternatives?
return path.dirname(process.execPath);
}
}
function evalScript(name) {
const Module = NativeModule.require('module');
const path = NativeModule.require('path');
const cwd = tryGetCwd(path);
const module = new Module(name);
module.filename = path.join(cwd, name);
module.paths = Module._nodeModulePaths(cwd);
const body = process._eval;
const script = `global.__filename = ${JSON.stringify(name)};\n` +
'global.exports = exports;\n' +
'global.module = module;\n' +
'global.__dirname = __dirname;\n' +
'global.require = require;\n' +
'return require("vm").runInThisContext(' +
`${JSON.stringify(body)}, { filename: ` +
`${JSON.stringify(name)}, displayErrors: true });\n`;
const result = module._compile(script, `${name}-wrapper`);
if (process._print_eval) console.log(result);
// Handle any nextTicks added in the first tick of the program.
process._tickCallback();
}
// Load preload modules
function preloadModules() {
if (process._preload_modules) {
NativeModule.require('module')._preloadModules(process._preload_modules);
}
}
function checkScriptSyntax(source, filename) {
const Module = NativeModule.require('module');
const vm = NativeModule.require('vm');
const internalModule = NativeModule.require('internal/module');
// remove Shebang
source = internalModule.stripShebang(source);
// remove BOM
source = internalModule.stripBOM(source);
// wrap it
source = Module.wrap(source);
// compile the script, this will throw if it fails
new vm.Script(source, { displayErrors: true, filename });
}
// Below you find a minimal module system, which is used to load the node
// core modules found in lib/*.js. All core modules are compiled into the
// node binary, so they can be loaded faster.
const ContextifyScript = process.binding('contextify').ContextifyScript;
function runInThisContext(code, options) {
const script = new ContextifyScript(code, options);
vm, core, module: re-do vm to fix known issues As documented in #3042 and in [1], the existing vm implementation has many problems. All of these are solved by @brianmcd&#39;s [contextify][2] package. This commit uses contextify as a conceptual base and its code core to overhaul the vm module and fix its many edge cases and caveats. Functionally, this fixes #3042. In particular: - A context is now indistinguishable from the object it is based on (the &#34;sandbox&#34;). A context is simply a sandbox that has been marked by the vm module, via `vm.createContext`, with special internal information that allows scripts to be run inside of it. - Consequently, items added to the context from anywhere are immediately visible to all code that can access that context, both inside and outside the virtual machine. This commit also smooths over the API very slightly: - Parameter defaults are now uniformly triggered via `undefined`, per ES6 semantics and previous discussion at [3]. - Several undocumented and problematic features have been removed, e.g. the conflation of `vm.Script` with `vm` itself, and the fact that `Script` instances also had all static `vm` methods. The API is now exactly as documented (although arguably the existence of the `vm.Script` export is not yet documented, just the `Script` class itself). In terms of implementation, this replaces node_script.cc with node_contextify.cc, which is derived originally from [4] (see [5]) but has since undergone extensive modifications and iterations to expose the most useful C++ API and use the coding conventions and utilities of Node core. The bindings exposed by `process.binding(&#39;contextify&#39;)` (node_contextify.cc) replace those formerly exposed by `process.binding(&#39;evals&#39;)` (node_script.cc). They are: - ContextifyScript(code, [filename]), with methods: - runInThisContext() - runInContext(sandbox, [timeout]) - makeContext(sandbox) From this, the vm.js file builds the entire documented vm module API. node.js and module.js were modified to use this new native binding, or the vm module itself where possible. This introduces an extra line or two into the stack traces of module compilation (and thus into most stack traces), explaining the changed tests. The tests were also updated slightly, with all vm-related simple tests consolidated as test/simple/test-vm-* (some of them were formerly test/simple/test-script-*). At the same time they switched from `common.debug` to `console.error` and were updated to use `assert.throws` instead of rolling their own error-testing methods. New tests were also added, of course, demonstrating the new capabilities and fixes. [1]: http://nodejs.org/docs/v0.10.16/api/vm.html#vm_caveats [2]: https://github.com/brianmcd/contextify [3]: https://github.com/joyent/node/issues/5323#issuecomment-20250726 [4]: https://github.com/kkoopa/contextify/blob/bf123f3ef960f0943d1e30bda02e3163a004e964/src/contextify.cc [5]: https://gist.github.com/domenic/6068120
12 years ago
return script.runInThisContext();
}
function NativeModule(id) {
this.filename = `${id}.js`;
this.id = id;
this.exports = {};
this.loaded = false;
this.loading = false;
}
NativeModule._source = process.binding('natives');
NativeModule._cache = {};
http2: introducing HTTP/2 At long last: The initial *experimental* implementation of HTTP/2. This is an accumulation of the work that has been done in the nodejs/http2 repository, squashed down to a couple of commits. The original commit history has been preserved in the nodejs/http2 repository. This PR introduces the nghttp2 C library as a new dependency. This library provides the majority of the HTTP/2 protocol implementation, with the rest of the code here providing the mapping of the library into a usable JS API. Within src, a handful of new node_http2_*.c and node_http2_*.h files are introduced. These provide the internal mechanisms that interface with nghttp and define the `process.binding(&#39;http2&#39;)` interface. The JS API is defined within `internal/http2/*.js`. There are two APIs provided: Core and Compat. The Core API is HTTP/2 specific and is designed to be as minimal and as efficient as possible. The Compat API is intended to be as close to the existing HTTP/1 API as possible, with some exceptions. Tests, documentation and initial benchmarks are included. The `http2` module is gated by a new `--expose-http2` command line flag. When used, `require(&#39;http2&#39;)` will be exposed to users. Note that there is an existing `http2` module on npm that would be impacted by the introduction of this module, which is the main reason for gating this behind a flag. When using `require(&#39;http2&#39;)` the first time, a process warning will be emitted indicating that an experimental feature is being used. To run the benchmarks, the `h2load` tool (part of the nghttp project) is required: `./node benchmarks/http2/simple.js benchmarker=h2load`. Only two benchmarks are currently available. Additional configuration options to enable verbose debugging are provided: ``` $ ./configure --debug-http2 --debug-nghttp2 $ NODE_DEBUG=http2 ./node ``` The `--debug-http2` configuration option enables verbose debug statements from the `src/node_http2_*` files. The `--debug-nghttp2` enables the nghttp library&#39;s own verbose debug output. The `NODE_DEBUG=http2` enables JS-level debug output. The following illustrates as simple HTTP/2 server and client interaction: (The HTTP/2 client and server support both plain text and TLS connections) ```jt client = http2.connect(&#39;http://localhost:80&#39;); const req = client.request({ &#39;:path&#39;: &#39;/some/path&#39; }); req.on(&#39;data&#39;, (chunk) =&gt; { /* do something with the data */ }); req.on(&#39;end&#39;, () =&gt; { client.destroy(); }); // Plain text (non-TLS server) const server = http2.createServer(); server.on(&#39;stream&#39;, (stream, requestHeaders) =&gt; { stream.respond({ &#39;:status&#39;: 200 }); stream.write(&#39;hello &#39;); stream.end(&#39;world&#39;); }); server.listen(80); ``` ```js const http2 = require(&#39;http2&#39;); const client = http2.connect(&#39;http://localhost&#39;); ``` Author: Anna Henningsen &lt;anna@addaleax.net&gt; Author: Colin Ihrig &lt;cjihrig@gmail.com&gt; Author: Daniel Bevenius &lt;daniel.bevenius@gmail.com&gt; Author: James M Snell &lt;jasnell@gmail.com&gt; Author: Jun Mukai Author: Kelvin Jin Author: Matteo Collina &lt;matteo.collina@gmail.com&gt; Author: Robert Kowalski &lt;rok@kowalski.gd&gt; Author: Santiago Gimeno &lt;santiago.gimeno@gmail.com&gt; Author: Sebastiaan Deckers &lt;sebdeckers83@gmail.com&gt; Author: Yosuke Furukawa &lt;yosuke.furukawa@gmail.com&gt; PR-URL: https://github.com/nodejs/node/pull/14239 Reviewed-By: Anna Henningsen &lt;anna@addaleax.net&gt; Reviewed-By: Colin Ihrig &lt;cjihrig@gmail.com&gt; Reviewed-By: Matteo Collina &lt;matteo.collina@gmail.com&gt;
8 years ago
const config = process.binding('config');
if (!config.exposeHTTP2)
delete NativeModule._source.http2;
NativeModule.require = function(id) {
if (id === 'native_module') {
return NativeModule;
}
const cached = NativeModule.getCached(id);
if (cached && (cached.loaded || cached.loading)) {
return cached.exports;
}
if (!NativeModule.exists(id)) {
// Model the error off the internal/errors.js model, but
// do not use that module given that it could actually be
// the one causing the error if there's a bug in Node.js
const err = new Error(`No such built-in module: ${id}`);
err.code = 'ERR_UNKNOWN_BUILTIN_MODULE';
err.name = 'Error [ERR_UNKNOWN_BUILTIN_MODULE]';
throw err;
}
process.moduleLoadList.push(`NativeModule ${id}`);
const nativeModule = new NativeModule(id);
nativeModule.cache();
nativeModule.compile();
return nativeModule.exports;
};
NativeModule.getCached = function(id) {
return NativeModule._cache[id];
};
NativeModule.exists = function(id) {
return NativeModule._source.hasOwnProperty(id);
};
if (config.exposeInternals) {
NativeModule.nonInternalExists = NativeModule.exists;
NativeModule.isInternal = function(id) {
return false;
};
} else {
NativeModule.nonInternalExists = function(id) {
return NativeModule.exists(id) && !NativeModule.isInternal(id);
};
NativeModule.isInternal = function(id) {
return id.startsWith('internal/');
};
}
NativeModule.getSource = function(id) {
return NativeModule._source[id];
};
NativeModule.wrap = function(script) {
return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];
};
NativeModule.wrapper = [
'(function (exports, require, module, __filename, __dirname) { ',
'\n});'
];
NativeModule.prototype.compile = function() {
var source = NativeModule.getSource(this.id);
source = NativeModule.wrap(source);
this.loading = true;
try {
const fn = runInThisContext(source, {
filename: this.filename,
lineOffset: 0,
displayErrors: true
});
fn(this.exports, NativeModule.require, this, this.filename);
this.loaded = true;
} finally {
this.loading = false;
}
};
NativeModule.prototype.cache = function() {
NativeModule._cache[this.id] = this;
};
startup();
});