如何用pkg打包nodejs可執(zhí)行文件?下面本篇文章給大家介紹一下使用pkg將Node項目打包為可執(zhí)行文件的方法,希望對大家有所幫助!
node.js極速入門課程:進入學習
使用pkg可以將Node.js項目打包為可執(zhí)行文件,甚至可以在未安裝Node.js的設備上運行?!鞠嚓P教程推薦:nodejs視頻教程】
實驗環(huán)境
-
操作系統(tǒng):windows
-
node版本: 16.14.2
操作過程
-
下載PKG
咱們可以選擇全局安裝,在任意目錄執(zhí)行:
$ npm install -g pkg
-
打包程序
先寫一個簡單的程序,比如server.js內(nèi)容
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項目根目錄,執(zhí)行如下命令
$ 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'
大意是,當前環(huán)境只支持編譯為windows系統(tǒng)的可執(zhí)行文件,也就是win
調(diào)整指令為:
$ 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、去官網(wǎng)下載相應版本文件,比如我的是node-v16.14.2-win-x64
官網(wǎng)地址:https://github.com/vercel/pkg-fetch/releases
2、將上一步下載的文件node-v16.14.2-win-x64重命名為fetched-v16.14.2-win-x64,放到當前用戶的緩存目錄中。
比如我的緩存目錄是C:UsersMangoDowner.pkg-cache,拼接上fetch的tag就變成了最終的目錄,參照報錯中的信息,可以得到tag為v3.3
{"tag":"v3.3","name":"node-v16.14.2-win-x64"}
咱們可以得到最終的父目錄為C:UsersMangoDowner.pkg-cachev3.3,
所以最終的文件地址為C:UsersMangoDowner.pkg-cachev3.3fetched-v16.14.2-win-x64
再次編譯,成功!
$ pkg -t win server.js > pkg@5.6.0