Node.js 作为 sidecar
在本指南中,我们将把一个 Node.js 应用打包成一个自包含的二进制文件,以便在 Tauri 应用中用作 sidecar,而无需终端用户安装 Node.js。本示例教程仅适用于桌面操作系统。
¥In this guide we are going to package a Node.js application to a self contained binary to be used as a sidecar in a Tauri application without requiring the end user to have a Node.js installation. This example tutorial is applicable for desktop operating systems only.
我们建议先阅读通用 sidecar 指南,以更深入地了解 Tauri sidecar 的工作原理。
¥We recommend reading the general sidecar guide first for a deeper understanding of how Tauri sidecars work.
¥Goals
-
将 Node.js 应用打包为二进制文件。
¥Package a Node.js application as a binary.
-
将此二进制文件集成为 Tauri sidecar。
¥Integrate this binary as a Tauri sidecar.
¥Implementation Details
-
为此,我们使用 pkg 工具,但任何其他可以将 JavaScript 或 Typescript 编译为二进制应用的工具都可以使用。
¥For this we use the pkg tool, but any other tool that can compile JavaScript or Typescript into a binary application will work.
-
你也可以将 Node 运行时本身嵌入到你的 Tauri 应用中,并将打包的 JavaScript 作为资源发送,但这会将 JavaScript 内容发送为可读文件,并且运行时通常比
pkg打包的应用更大。¥You can also embed the Node runtime itself into your Tauri application and ship bundled JavaScript as a resource, but this will ship the JavaScript content as readable-ish files and the runtime is usually larger than a
pkgpackaged application.
在此示例中,我们将创建一个 Node.js 应用,该应用从命令行 process.argv 读取输入并使用 console.log 将输出写入 stdout。
你可以利用其他进程间通信系统,例如本地服务器、stdin/stdout 或本地套接字。请注意,每个都有自己的优点、缺点和安全问题。
¥In this example we will create a Node.js application that reads input from the command line process.argv
and writes output to stdout using console.log.
You can leverage alternative inter-process communication systems such as a localhost server, stdin/stdout or local sockets.
Note that each has their own advantages, drawbacks and security concerns.
¥Prerequisites
使用 shell 插件设置的现有 Tauri 应用,可在本地为你编译和运行。
¥An existing Tauri application set up with the shell plugin, that compiles and runs for you locally.
:::note 注意
请首先按照 shell 插件指南 正确设置和初始化插件。如果插件未初始化和配置,示例将无法运行。
¥Please follow the shell plugin guide first to set up and initialize the plugin correctly. Without the plugin being initialized and configured the example won’t work.
:::
¥Guide
-
Let’s create a new Node.js project to contain our sidecar implementation. Create a new directory in your Tauri application root folder (in this example we will call it
sidecar-app) and run theinitcommand of your preferred Node.js package manager inside the directory:npm inityarn initpnpm initWe will compile our Node.js application to a self container binary using pkg among other options. Let’s install it as a development dependency into the new
sidecar-app:npm add @yao-pkg/pkg --save-devyarn add @yao-pkg/pkg --devpnpm add @yao-pkg/pkg --save-dev -
Now we can start writing JavaScript code that will be executed by our Tauri application.
In this example we will process a command from the command line argmuents and write output to stdout, which means our process will be short lived and only handle a single command at a time. If your application must be long lived, consider using alternative inter-process communication systems.
Let’s create a
index.jsfile in oursidecar-appdirectory and write a basic Node.js app:sidecar-app/index.js const command = process.argv[2];switch (command) {case 'hello':const message = process.argv[3];console.log(`Hello ${message}!`);break;default:console.error(`unknown command ${command}`);process.exit(1);} -
To package our Node.js application into a self contained binary, create a script in
package.json:sidecar-app/package.json {"scripts": {"build": "pkg index.ts --output my-sidecar"}}npm run buildyarn buildpnpm buildThis will create the
sidecar-app/my-sidecarbinary on Linux and macOS, and asidecar-app/my-sidecar.exeexecutable on Windows.For sidecar applications, we need to ensure that the binary is named in the correct pattern, for more information read Embedding External Binaries To rename this file to the expected Tauri sidecar filename and also move to our Tauri project, we can use the following Node.js script as a starting example:
sidecar-app/rename.js import { execSync } from 'child_process';import fs from 'fs';const ext = process.platform === 'win32' ? '.exe' : '';const rustInfo = execSync('rustc -vV');const targetTriple = /host: (\S+)/g.exec(rustInfo)[1];if (!targetTriple) {console.error('Failed to determine platform target triple');}// TODO: create `src-tauri/binaries` dirfs.renameSync(`my-sidecar${ext}`,`../src-tauri/binaries/my-sidecar-${targetTriple}${ext}`);And run
node rename.jsfrom thesidecar-appdirectory.At this step the
/src-tauri/binariesdirectory should contain the renamed sidecar binary. -
After installing the shell plugin make sure you configure the required capabilities.
Note that we use
"args": truebut you can optionally provide an array["hello"], read more.src-tauri/capabilities/default.json {"permissions": ["core:default","opener:default",{"identifier": "shell:allow-execute","allow": [{"args": true,"name": "binaries/my-sidecar","sidecar": true}]}]} -
Configure the Sidecar in the Tauri Application
Section titled “Configure the Sidecar in the Tauri Application”Now that we have our Node.js application ready, we can connect it to our Tauri application by configuring the
bundle > externalBinarray:src-tauri/tauri.conf.json {"bundle": {"externalBin": ["binaries/my-sidecar"]}}The Tauri CLI will handle the bundling of the sidecar binary as long as it exists as
src-tauri/binaries/my-sidecar-<target-triple>. -
We can run the sidecar binary either from Rust code or directly from JavaScript.
Let’s execute the
hellocommand in the Node.js sidecar directly:import { Command } from '@tauri-apps/plugin-shell';const message = 'Tauri';const command = Command.sidecar('binaries/my-sidecar', ['hello', message]);const output = await command.execute();// once everything is configured it should log "Hello Tauri" in the browser console.console.log(output.stdout)Let’s pipe a
helloTauri command to the Node.js sidecar:use tauri_plugin_shell::ShellExt;#[tauri::command]async fn hello(app: tauri::AppHandle, cmd: String, message: String) -> String {let sidecar_command = app.shell().sidecar("my-sidecar").unwrap().arg(cmd).arg(message);let output = sidecar_command.output().await.unwrap();String::from_utf8(output.stdout).unwrap()}Register it in
invoke_handlerand call it in the frontend with:import { invoke } from "@tauri-apps/api/core";const message = "Tauri"console.log(await invoke("hello", { cmd: 'hello', message })) -
Lets test it
npm run tauri devyarn tauri devpnpm tauri devdeno task tauri devbun tauri devcargo tauri devOpen the DevTools with F12 (or
Cmd+Option+Ion macOS) and you should see the output of the sidecar command.If you find any issues, please open an issue on GitHub.
Tauri v2.9 中文网 - 粤ICP备13048890号
Nodejs.cn 旗下网站