需要在没有node环境的电脑上运行node程序
打包工具安装npm install -g pkg
pkg server.js
pkg -t win server.js
-
npm install -g pkg :全局安装pkg
-
pkg server.js : 将 api.js 编译成 api.exe 可执行文件
-
pkg -t win server.js : 上面的命令会同时编译出 linux 、windows 、mac 版的 exe,加 -t win 就可以只编译 windows 下的
//server.js
//用express做的简单服务
const express = require("express");
const app = express();
const path = require("path");
app.use(express.static(path.join(__dirname, "dist"))); //注意这里使用path.join(__dirname, 'dist')而不是'dist',虽然在命令行中执行起来效果是一样的,不过pkg打包会无法识别到dist目录
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log(`AIbuy agents server start successfully on http://${host}:${port}`);
});
编译完成后,会生成server.exe文件,双击该文件,浏览器访问http://localhost:8081即可
注意在编译的过程中(pkg -t win server.js)可能会出现报错的情况,如下
> pkg@4.3.0
> Fetching base Node.js binaries to PKG_CACHE_PATH
fetched-v12.18.1-win-x64 [ ] 0%
> Error! connect ETIMEDOUT 13.229.188.59:443
> Asset not found by direct link:
{"tag":"v2.6","name":"uploaded-v2.6-node-v12.18.1-win-x64"}
这是因为编译的时候要从github下载uploaded-v2.6-node-v12.18.1-win-x64包,由于下载不了导致的,
这时我们可以先去github下载到这个包,放到当前用户下,如C:\Users\cheng\.pkg-cache\v2.6
,让包的名字改为 fetched-v12.18.1-win-x64 ,再次运行编译即可。
要下载什么版本的包看自己的报错需要什么版本。
github地址:https://github.com/vercel/pkg-fetch/releases
其他注意项如果有些配置文件,不想被打包进 exe
文件中,而是想把部分配置文件放在外面可被修改,则可以使用 process.cwd()
来引用文件
const port = require(process.cwd() + '/port');
// 不过编译的时候,pkg 有告警提示
Dynamic require may fail at run time, because the requested file
is unknown at compilation time and not included into executable.
Use a string literal as an argument for 'require', or leave it
as is and specify the resolved file name in 'scripts' option.
process.cwd()
和 __diranme
的区别可以参考这文章: process.cwd()和__dirname的区别
Pkg —— 打包node为可执行文件(.exe)工具 - 掘金