當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js globalPreload()用法及代碼示例

globalPreload()

加載程序 API 正在重新設計。這個鉤子可能會消失,或者它的簽名可能會改變。不要依賴下麵說明的 API。

在此 API 的先前版本中,此鉤子被命名為 getGlobalPreloadCode

有時可能需要在應用程序運行所在的同一全局範圍內運行一些代碼。此鉤子允許返回一個字符串,該字符串在啟動時作為 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);
    };
  `;
}

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 globalPreload()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。