编程知识 cdmana.com

How to node JS project is packaged as an executable file

How to integrate Node.js The project is packaged as an executable

PKG
  • pkg Can be Node.js The project is packaged as a separate executable , Can be installed without Nodejs Running on the machine . Support win、linux Isochromatic system .
  • pkg The principle of packaging is simple , Will be js The code and related resource files are packaged into executable files , And then hijack it fs Some of the functions in it , Enable it to read the code and resource files in the executable file .
usage

pkg It's easy to use , Under execution pkg -h You can basically understand the usage , The basic grammar is :pkg [options] <input>

<input> You can specify... In three ways :

1. A script file , for example pkg index.js;
2.package.json, for example pkg package.json, In this case, we will use package.json Medium bin Field as the entry file ;
3. A directory , for example pkg ., At this time, it will look for... In the specified directory package.json file , And looking for bin Field as the entry file .

[options] Package parameters can be specified in :
1.-t Specify the packaged target platform and Node edition , Such as -t node6-win-x64,node6-linux-x64,node6-macos-x64 Can be packaged at the same time 3 An executable program for a platform ;
2.-o Specify the name of the output executable , But if use -t Multiple targets specified , Then use --out-path Specify the output directory ;
3.-c To specify a JSON The configuration file , Used to specify additional packaged scripts and resource files , Usually use package.json To configure .

Use :

stay package.json Medium pkg Specify the packaging parameters in the field , Use npm scripts To perform the packaging process , for example :

{
...
"scripts": {
"build": "pkg index.js"
}
}

About configuration file processing in the project , Such as environment variables, etc . Because these configuration files will change with different deployment environments , So for the convenience of change , Generally, you don't want to package the configuration file into exe. for fear of pkg Automatically package configuration files into exe in , Don't use... In your code __dirname, Instead, it is used relative to process.cwd() Method to read :

//  Not recommended 
const config = require((path.join(__dirname, './config.js'))
 
//  recommend 
const config = require(path.join(process.cwd(), './config.js'));

版权声明
本文为[nut loaves ]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/12/202112122212497211.html

Scroll to Top