globalPreload()
加载程序 API 正在重新设计。这个钩子可能会消失,或者它的签名可能会改变。不要依赖下面说明的 API。
在此 API 的先前版本中,此钩子被命名为 getGlobalPreloadCode
。
- 返回: <string>
有时可能需要在应用程序运行所在的同一全局范围内运行一些代码。此钩子允许返回一个字符串,该字符串在启动时作为 sloppy-mode 脚本运行。
与CommonJS 包装器的工作方式类似,代码在隐式函数范围内运行。唯一的参数是一个类似于 require
的函数,可用于加载像 "fs": getBuiltin(request: string)
这样的内置函数。
如果代码需要更高级的 require
函数,则必须使用 module.createRequire()
构建自己的 require
。
/**
* @param {{
port: MessagePort,
}} utilities Things that preload code might find useful
* @returns {string} Code to run before application startup
*/
export function globalPreload(utilities) {
return `\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');
const { createRequire } = getBuiltin('module');
const { cwd } = getBuiltin('process');
const require = createRequire(cwd() + '/<preload>');
// [...]
`;
}
为了允许应用程序和加载程序之间进行通信,预加载代码提供了另一个参数:port
。这可作为 loader 钩子的参数和钩子返回的源文本内部使用。必须注意正确调用
和port.ref()
以防止进程处于无法正常关闭的状态。port.unref()
/**
* This example has the application context send a message to the loader
* and sends the message back to the application context
* @param {{
port: MessagePort,
}} utilities Things that preload code might find useful
* @returns {string} Code to run before application startup
*/
export function globalPreload({ port }) {
port.onmessage = (evt) => {
port.postMessage(evt.data);
};
return `\
port.postMessage('console.log("I went to the Loader and back");');
port.onmessage = (evt) => {
eval(evt.data);
};
`;
}
相关用法
- Node.js ServerHttp2Stream http2stream.pushStream(headers[, options], callback)用法及代码示例
- Node.js http2.Http2ServerRequest request.url用法及代码示例
- Node.js request.socket用法及代码示例
- Node.js assert.notEqual(actual, expected[, message])用法及代码示例
- Node.js tlsSocket.authorized用法及代码示例
- Node.js zlib.deflateRaw()用法及代码示例
- Node.js http.IncomingMessage message.rawHeaders用法及代码示例
- Node.js Console用法及代码示例
- Node.js GM transparent()用法及代码示例
- Node.js URL.protocol用法及代码示例
- Node.js http.Agent.reuseSocket(socket, request)用法及代码示例
- Node.js fs.filehandle.datasync()用法及代码示例
- Node.js socket.bind()用法及代码示例
- Node.js v8.getHeapSpaceStatistics()用法及代码示例
- Node.js http2session.destroyed用法及代码示例
- Node.js http.ServerResponse response.statusCode用法及代码示例
- Node.js Buffer buf.writeBigUInt64BE(value[, offset])用法及代码示例
- Node.js Http2ServerResponse.finished用法及代码示例
- Node.js Http2Stream close用法及代码示例
- Node.js readStream.isRaw用法及代码示例
- Node.js diffieHellman.getGenerator()用法及代码示例
- Node.js util.types.isInt16Array(value)用法及代码示例
- Node.js certificate.verifySpkac(spkac[, encoding])用法及代码示例
- Node.js util.types.isNativeError(value)用法及代码示例
- Node.js assert.notDeepStrictEqual(actual, expected[, message])用法及代码示例
注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 globalPreload()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。