单个可执行应用
【Single executable applications】
源代码: 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 二进制文件注入 JavaScript 文件来创建 单个可执行应用。在启动过程中,程序会检查是否有任何文件被注入。如果找到了脚本,它会执行其中的内容。否则,Node.js 会照常运行。
【Node.js supports the creation of single executable applications by allowing
the injection of a JavaScript file into the node binary. During start up, the
program checks if anything has been injected. If the script is found, it
executes its contents. Otherwise Node.js operates as it normally does.】
单一可执行应用功能仅支持运行单个嵌入的 CommonJS 文件。
【The single executable application feature only supports running a single embedded CommonJS file.】
一个打包的 JavaScript 文件可以通过任何可以向 node 二进制文件注入资源的工具转换成一个单一的可执行应用。
【A bundled JavaScript file can be turned into a single executable application
with any tool which can inject resources into the node binary.】
以下是使用其中一个工具 后投 创建单个可执行应用的步骤:
【Here are the steps for creating a single executable application using one such tool, postject:】
-
创建一个 JavaScript 文件:
$ echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js -
创建一个
node可执行文件的副本,并根据你的需要命名:$ cp $(command -v node) hello -
移除二进制文件的签名:
- 在 macOS 上:
$ codesign --remove-signature hello- 在 Windows 上(可选):
签名工具 可以从已安装的 Windows 软件开发工具包 使用。如果跳过此步骤,请忽略来自 postject 的任何与签名相关的警告。
$ signtool remove /s hello -
通过使用以下选项运行
postject将 JavaScript 文件注入复制的二进制文件:hello- 在第 2 步中创建的node可执行文件副本的名称。NODE_JS_CODE- 二进制文件中存放 JavaScript 文件内容的资源/注释/部分的名称。hello.js- 在步骤 1 中创建的 JavaScript 文件的名称。--sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2- Node.js 项目用来检测文件是否被注入的 保险丝。--macho-segment-name NODE_JS(仅在 macOS 上需要)- 二进制文件中存储 JavaScript 文件内容的段的名称。
总而言之,这是每个平台所需的命令:
-
在 macOS 以外的系统上:
$ npx postject hello NODE_JS_CODE hello.js \ --sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2 -
在 macOS 上:
$ npx postject hello NODE_JS_CODE hello.js \ --sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ --macho-segment-name NODE_JS
-
签署二进制文件:
- 在 macOS 上:
$ codesign --sign - hello- 在 Windows 上(可选):
要使其工作,需要提供证书。然而,未签名的二进制文件仍然可以运行。
$ signtool sign /fd SHA256 hello -
运行二进制文件:
$ ./hello world Hello, world!