关于node.js:如何用pkg打包nodejs可执行文件

5次阅读

共计 1669 个字符,预计需要花费 5 分钟才能阅读完成。

应用 pkg 能够将 Node.js 我的项目打包为可执行文件,甚至能够在未装置 Node.js 的设施上运行。

试验环境

操作系统:windows
node 版本: 16.14.2

操作过程

  1. 下载 PKG

咱们能够抉择全局装置,在任意目录执行:

$ npm install -g pkg
  1. 打包程序

先写一个简略的程序,比方 server.js 内容

const express = require('express');
const app = express();

app.get('/', (req, res) => {res.send('Hello World!');
});

app.listen(3000, () => {console.log('Express web app on localhost:3000');
});

进入 nodejs 我的项目根目录,执行如下命令

$ pkg server.js

第一次报错

这时候会报错

$ pkg server.js
> pkg@5.6.0
> Targets not specified. Assuming:
  node16-linux-x64, node16-macos-x64, node16-win-x64
> Fetching base Node.js binaries to PKG_CACHE_PATH
  fetched-v16.14.2-linux-x64          [ ] 0%> Not found in remote cache:
  {"tag":"v3.3","name":"node-v16.14.2-linux-x64"}
> Building base binary from source:
  built-v16.14.2-linux-x64
> Error! Not able to build for 'linux' here, only for 'win'

粗心是,以后环境只反对编译为 windows 零碎的可执行文件,也就是 win

调整指令为:

$ pkg -t win server.js

其中 -t win 等同于 –targets win,也就是说只为 windows 编译文件。

第二次报错

编译时候再次报错:

$ pkg -t win server.js
> pkg@5.6.0
> Fetching base Node.js binaries to PKG_CACHE_PATH
  fetched-v16.14.2-win-x64            [ ] 0%> Not found in remote cache:
  {"tag":"v3.3","name":"node-v16.14.2-win-x64"}
> Building base binary from source:
  built-v16.14.2-win-x64
> Fetching Node.js source archive from nodejs.org...
> Error! AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

粗心是缓存里短少相应的二进制文件 fetched-v16.14.2-win-x64,咱们只有下载到相应的文件,放到相应的缓存目录就好。

1、去 官网 下载相应版本文件,比方我的是 node-v16.14.2-win-x64

官网地址:https://github.com/vercel/pkg…

2、将上一步下载的文件 node-v16.14.2-win-x64 重命名为 fetched-v16.14.2-win-x64, 放到以后用户的缓存目录中。

比方我的缓存目录是C:\Users\MangoDowner.pkg-cache,拼接上 fetch 的 tag 就变成了最终的目录,参照报错中的信息,能够失去 tag 为 v3.3

 {"tag":"v3.3","name":"node-v16.14.2-win-x64"}

咱们能够失去最终的父目录为 C:\Users\MangoDowner.pkg-cache\v3.3,
所以最终的文件地址为 C:\Users\MangoDowner.pkg-cache\v3.3\fetched-v16.14.2-win-x64

再次编译,胜利!

$ pkg -t win server.js
> pkg@5.6.0
正文完
 0