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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。