正在运行的钩子
【Running hooks】
# main.coffee
import { scream } from './scream.coffee'
console.log scream 'hello, world'
import { version } from 'node:process'
console.log "Brought to you by Node.js version #{version}" # scream.coffee
export scream = (str) -> str.toUpperCase() 为了运行示例,添加一个包含 CoffeeScript 文件模块类型的 package.json 文件。
【For the sake of running the example, add a package.json file containing the
module type of the CoffeeScript files.】
{
"type": "module"
} 这仅用于运行示例。在实际的加载器中,即使在 package.json 中没有显式的类型,getPackageType() 也必须能够返回 Node.js 已知的 format,否则 nextLoad 调用将抛出 ERR_UNKNOWN_FILE_EXTENSION(如果未定义)或 ERR_UNKNOWN_MODULE_FORMAT(如果它不是 加载钩子 文档中列出的已知格式)。
【This is only for running the example. In real world loaders, getPackageType() must be
able to return an format known to Node.js even in the absence of an explicit type in a
package.json, or otherwise the nextLoad call would throw ERR_UNKNOWN_FILE_EXTENSION
(if undefined) or ERR_UNKNOWN_MODULE_FORMAT (if it's not a known format listed in
the load hook documentation).】
使用前面的钩子模块,运行
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee
或者 node --import ./coffeescript-sync-hooks.mjs ./main.coffee
会在从磁盘加载 main.coffee 的源代码后,但在 Node.js 执行之前,将其转换为 JavaScript;对于通过 import 语句引用的任何已加载文件的 .coffee、.litcoffee 或 .coffee.md 文件也同样适用。
【With the preceding hooks modules, running
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee
or node --import ./coffeescript-sync-hooks.mjs ./main.coffee
causes main.coffee to be turned into JavaScript after its source code is
loaded from disk but before Node.js executes it; and so on for any .coffee,
.litcoffee or .coffee.md files referenced via import statements of any
loaded file.】