12

Using pkg, Node.js projects can be packaged into executables that can even be run on devices that don't have Node.js installed.

lab environment

Operating system: windows
node version: 16.14.2

Operation process

  1. Download PKG

We can choose to install globally and execute in any directory:

 $ npm install -g pkg
  1. packager

Write a simple program first, such as server.js content

 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');
});

Go to the root directory of the nodejs project and execute the following command

 $ pkg server.js

first error

At this time, it will report an error

 $ 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'

The general idea is that the current environment only supports executable files compiled for the windows system, that is, win

The adjustment command is:

 $ pkg -t win server.js

Where -t win is equivalent to --targets win, which means that the file is only compiled for windows.

second error

Error again when compiling:

 $ 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:

The general idea is that the corresponding binary file fetched-v16.14.2-win-x64 is missing in the cache. We just need to download the corresponding file and put it in the corresponding cache directory.

1. Go to the official website to download the corresponding version file, for example, mine is node-v16.14.2-win-x64

Official website address: https://github.com/vercel/pkg-fetch/releases

image.png

2. Rename the file node-v16.14.2-win-x64 downloaded in the previous step to fetched-v16.14.2-win-x64 and put it in the cache directory of the current user.

For example, my cache directory is C:\Users\MangoDowner.pkg-cache , and the fetched tag becomes the final directory. Referring to the information in the error report, the tag can be obtained as v3.3

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

We can get the final parent directory as C:\Users\MangoDowner.pkg-cache\v3.3,
So the final file address is C:\Users\MangoDowner.pkg-cache\v3.3\fetched-v16.14.2-win-x64

Compile again, success!

 $ pkg -t win server.js
> pkg@5.6.0

墨城
1.7k 声望2.1k 粉丝