单个可执行应用


🌐 Single executable applications

稳定性: 1.1 - 处于活跃开发中

源代码: src/node_sea.cc

此功能允许方便地将 Node.js 应用分发到未安装 Node.js 的系统上。

🌐 This feature allows the distribution of a Node.js application conveniently to a system that does not have Node.js installed.

Node.js 支持通过允许注入由 Node.js 准备的 blob 来创建 单个可执行应用,该 blob 可以包含打包的脚本,注入到 node 二进制文件中。在启动期间,程序会检查是否有任何内容被注入。如果找到了 blob,它会执行 blob 中的脚本。否则,Node.js 会像平常一样运行。

🌐 Node.js supports the creation of single executable applications by allowing the injection of a blob prepared by Node.js, which can contain a bundled script, into the node binary. During start up, the program checks if anything has been injected. If the blob is found, it executes the script in the blob. Otherwise Node.js operates as it normally does.

单个可执行应用功能支持使用 CommonJSECMAScript 模块 模块系统运行单个嵌入脚本。

🌐 The single executable application feature supports running a single embedded script using the CommonJS or the ECMAScript Modules module system.

用户可以使用 node 可执行文件本身以及任何可以将资源注入二进制文件的工具,从他们打包的脚本创建单个可执行应用。

🌐 Users can create a single executable application from their bundled script with the node binary itself and any tool which can inject resources into the binary.

  1. 创建一个 JavaScript 文件:

    echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js 
  2. 创建一个配置文件,用于构建可以注入到单个可执行应用中的 blob(详情见 生成单个可执行准备 blob):

    • 在非 Windows 系统上:
    echo '{ "main": "hello.js", "output": "sea" }' > sea-config.json 
    • 在 Windows 上:
    echo '{ "main": "hello.js", "output": "sea.exe" }' > sea-config.json 

    .exe 扩展名是必要的。

  3. 生成目标可执行文件:

    node --build-sea sea-config.json 
  4. 签署二进制文件(仅限 macOS 和 Windows):

    • 在 macOS 上:
    codesign --sign - hello 
    • 在 Windows 上(可选):

    要使其工作,需要提供证书。然而,未签名的二进制文件仍然可以运行。

    signtool sign /fd SHA256 hello.exe 
  5. 运行二进制文件:

    • 在非 Windows 系统上
    $ ./hello world
    Hello, world! 
    • 在 Windows 上
    $ .\hello.exe world
    Hello, world!