### Example pkg test file Source: https://github.com/yao-pkg/pkg/blob/main/DEVELOPMENT.md Illustrates a basic 'pkg' test structure in JavaScript. This example demonstrates using assertions to validate the script's execution context, employing utility functions for managing files, and invoking 'pkg' to process an input file while verifying the creation of expected output files. ```javascript #!/usr/bin/env node 'use strict'; const assert = require('assert'); const utils = require('../utils.js'); assert(!module.parent); assert(__dirname === process.cwd()); const input = './test-x-index'; const newcomers = [ 'test-x-index-linux', 'test-x-index-macos', 'test-x-index-win.exe', ]; const before = utils.filesBefore(newcomers); utils.pkg.sync([input], { stdio: 'inherit' }); utils.filesAfter(before, newcomers); ``` -------------------------------- ### Install Dependencies and Package Express Application Source: https://github.com/yao-pkg/pkg/blob/main/examples/express/readme.md Commands to install Node.js dependencies for the Express application and then package the entire application into a standalone executable using the `pkg` tool. ```shell npm install pkg . ``` -------------------------------- ### Run npm release command Source: https://github.com/yao-pkg/pkg/blob/main/DEVELOPMENT.md Executes the 'release' script defined in package.json. This command initiates an interactive process that guides the user through the project release using the 'release-it' tool. ```bash npm run release ``` -------------------------------- ### Build project with npm Source: https://github.com/yao-pkg/pkg/blob/main/DEVELOPMENT.md Compiles the project's source code. This step is a prerequisite for running tests and must be re-executed after any modifications to the source code located within the 'lib' folder. ```bash npm run build ``` -------------------------------- ### Install pkg CLI Globally Source: https://github.com/yao-pkg/pkg/blob/main/README.md Installs the `@yao-pkg/pkg` command-line interface globally using npm, making the `pkg` command available system-wide for packaging Node.js applications. ```Shell npm install -g @yao-pkg/pkg ``` -------------------------------- ### Execute pkg tests Source: https://github.com/yao-pkg/pkg/blob/main/DEVELOPMENT.md Runs the project's test suite. This command allows for specifying a target Node.js version, controlling the inclusion of npm-dependent tests, and filtering tests by a specific pattern or 'flavor'. ```bash node test/test.js [no-npm | only-npm | all] [] ``` -------------------------------- ### JavaScript Non-Literal Require and Path Examples Source: https://github.com/yao-pkg/pkg/blob/main/README.md Illustrates common JavaScript patterns, such as dynamic `require` calls and `path.join` for file paths, that `pkg` cannot automatically resolve. These patterns necessitate manual configuration in `package.json` to ensure all dependencies and assets are included. ```js require('./build/' + cmd + '.js'); path.join(__dirname, 'views/' + viewName); ``` -------------------------------- ### pkg Command Line Interface Reference Source: https://github.com/yao-pkg/pkg/blob/main/README.md Comprehensive documentation for the `pkg` CLI tool, detailing its syntax, available options with their descriptions, and practical examples demonstrating various packaging scenarios and configurations. It also explains how `pkg` interprets different types of input as entry points. ```APIDOC pkg CLI Syntax: pkg [options] Input Entrypoint: - Path to entry file (e.g., /path/app.js) - Path to package.json (pkg uses 'bin' property) - Path to directory (pkg looks for package.json) Options: -h, --help output usage information -v, --version output pkg version -t, --targets comma-separated list of targets (see examples) -c, --config package.json or any json file with top-level config --options bake v8 options into executable to run with them on -o, --output output file name or template for several files --out-path path to save output one or more executables -d, --debug show more information during packaging process [off] -b, --build don't download prebuilt base binaries, build them --public speed up and disclose the sources of top-level project --public-packages force specified packages to be considered public --no-bytecode skip bytecode generation and include source files as plain js --no-native-build skip native addons build --no-dict comma-separated list of packages names to ignore dictionaries. Use --no-dict * to disable all dictionaries -C, --compress [default=None] compression algorithm = Brotli or GZip --sea (Experimental) compile give file using node's SEA feature. Requires node v20.0.0 or higher and only single file is supported Examples: – Makes executables for Linux, macOS and Windows $ pkg index.js – Takes package.json from cwd and follows 'bin' entry $ pkg . – Makes executable for particular target machine $ pkg -t node14-win-arm64 index.js – Makes executables for target machines of your choice $ pkg -t node16-linux,node18-linux,node18-win index.js – Bakes '--expose-gc' and '--max-heap-size=34' into executable $ pkg --options \"expose-gc,max-heap-size=34\" index.js – Consider packageA and packageB to be public $ pkg --public-packages \"packageA,packageB\" index.js – Consider all packages to be public $ pkg --public-packages \"*\" index.js – Bakes '--expose-gc' into executable $ pkg --options expose-gc index.js – reduce size of the data packed inside the executable with GZip $ pkg --compress GZip index.js – compile the file using node's SEA feature. Creates executables for Linux, macOS and Windows $ pkg --sea index.js ``` -------------------------------- ### Loading Modules with Node.js `require()` Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Demonstrates the use of the Node.js `require()` function to load modules dynamically. This function loads and caches modules, and examples include loading without arguments, with module names, and with additional exclusion paths. ```JavaScript require(); require("barbos2"); require(`barbos2`); require(`barbos2`, `must-exclude2`); require("barbos2", "must-exclude2"); require("barbos2", "may-exclude2"); require("barbos2", "unknown2"); ``` -------------------------------- ### Resolving Module Paths with Node.js `require.resolve()` Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Illustrates the use of Node.js `require.resolve()` to get the resolved path of a module without actually loading it. Examples include resolving without arguments, with module names, and with additional exclusion paths, demonstrating its flexibility for checking module availability. ```JavaScript require.resolve(); require.resolve("barbos1"); require.resolve(`barbos1`); require.resolve(`barbos1`, `must-exclude1`); require.resolve("barbos1", "must-exclude1"); require.resolve("barbos1", "may-exclude1"); require.resolve("barbos1", "unknown1"); ``` -------------------------------- ### Embed Node.js Runtime Options with pkg Source: https://github.com/yao-pkg/pkg/blob/main/README.md Illustrates how to bake Node.js or V8 runtime options directly into a `pkg` packaged application using the `--options` flag. It shows examples of specifying single or multiple comma-separated options, which will always be active when the application runs. ```sh pkg app.js --options expose-gc ``` ```sh pkg app.js --options max_old_space_size=4096 ``` ```sh pkg app.js --options max-old-space-size=1024,tls-min-v1.0,expose-gc ``` -------------------------------- ### pkg Target Format Specification Source: https://github.com/yao-pkg/pkg/blob/main/README.md Describes the canonical format for specifying build targets for the `pkg` tool. Targets consist of a node range, platform, and architecture, separated by dashes. Examples illustrate valid combinations for different environments. ```APIDOC node18-macos-x64 node14-linux-arm64 ``` -------------------------------- ### Extract and Execute Binaries from pkg Snapshot Source: https://github.com/yao-pkg/pkg/blob/main/README.md This Node.js snippet demonstrates a method to extract and execute binaries that are embedded within a 'pkg' snapshot. It checks if the application is running as a 'pkg' executable, then copies a specified binary (e.g., FFmpeg) from its installed path to the current working directory, sets executable permissions, and finally executes it. This is necessary because 'pkg' executables require native binaries to be on disk to be run. ```js const cp = require('child_process'); const fs = require('fs'); const { pipeline } = require('stream/promises'); let ffmpeg = require('@ffmpeg-installer/ffmpeg').path; const loadPlugin = async () => { if (process.pkg) { // copy ffmpeg to the current directory const file = fs.createWriteStream('ffmpeg'); await pipeline(fs.createReadStream(ffmpeg), file); fs.chmodSync('ffmpeg', 0o755); console.log('ffmpeg copied to the current directory'); ffmpeg = './ffmpeg'; } cp.execSync(ffmpeg); }; loadPlugin(); ``` -------------------------------- ### Build and Run pkg Application in Debug Mode Source: https://github.com/yao-pkg/pkg/blob/main/README.md Demonstrates how to build a `pkg` executable with debug information and then run it with the `DEBUG_PKG` environment variable set to inspect the virtual file system. Examples are provided for both Linux/macOS and Windows environments, showing how to enable the VFS inspection feature. ```bash pkg --debug app.js -o output DEBUG_PKG=1 output ``` ```cmd C:\> pkg --debug app.js -o output.exe C:\> set DEBUG_PKG=1 C:\> output.exe ``` -------------------------------- ### Defining Global Constants in JavaScript Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Examples of defining global constants in JavaScript, including numeric values for positive and negative infinity, and an array of string literals. These constants are typically used for fixed values that are referenced throughout an application. ```JavaScript var INFINITY = 1 / 0; var NEGATIVE_INFINITY = -1 / 0; var group_names = [ , 'whitespace' // INTENTIONAL COMMA! , 'terminator' , 'string' , 'comment' , 'identifier' , 'preprocess' , 'operator' , 'invalid' ]; ``` -------------------------------- ### Exporting a String Value in CommonJS Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-package-json/test-y-resolve-B.txt This JavaScript snippet illustrates a fundamental CommonJS module export. It assigns a simple string literal to `module.exports`, making this string the value that will be returned when this module is `require()`d by another file. ```javascript module.exports = "test-y-resolve-B"; ``` -------------------------------- ### Implementing an IIFE for Scope Encapsulation Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt An example of an Immediately Invoked Function Expression (IIFE) used to create a private scope for variables and functions. This pattern prevents variables from polluting the global namespace and includes a labeled `for` loop with a `continue` statement for specific iteration control. ```JavaScript var inheritedDataKeys = (function() { var obj = {}; function hasProp(o, k) { return true; } enumeration: for (var key in obj) { if (!hasProp.call(obj, key)) { continue enumeration; } } })(); ``` -------------------------------- ### Exporting a String Value in Node.js Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-node-modules-tree/node_modules/test-y-fish-O/node_modules/test-y-fish-O/index.txt This snippet demonstrates a basic Node.js module export, where a string value is directly assigned to `module.exports`. This makes the string the default export of the module when it's `require()`d by another file. It's a common pattern for configuration values or simple constants. ```JavaScript module.exports = "test-y-fish-O-subpackage"; ``` -------------------------------- ### Set pkg Cache Path via Environment Variable Source: https://github.com/yao-pkg/pkg/blob/main/README.md These examples demonstrate two common ways to set the `PKG_CACHE_PATH` environment variable before running the `pkg` command. The first uses `export` for a persistent session setting, while the second sets it inline for a single command execution. ```bash # 1 - Using export export PKG_CACHE_PATH=/my/cache pkg app.js # 2 - Passing it before the script PKG_CACHE_PATH=/my/cache pkg app.js ``` -------------------------------- ### Automatic Asset Detection with path.join in pkg Source: https://github.com/yao-pkg/pkg/blob/main/README.md This snippet illustrates the specific pattern `pkg` recognizes for automatically packaging assets. When `path.join` is used with `__dirname` and a string literal for the second argument, `pkg` includes the referenced file in the executable's snapshot. This mechanism simplifies asset management by avoiding explicit `pkg` configuration. ```javascript path.join(__dirname, '../path/to/asset') ``` -------------------------------- ### Comparison of Path Variables in Node.js vs. pkg Packaged Apps Source: https://github.com/yao-pkg/pkg/blob/main/README.md This table illustrates how common path-related variables like `__filename`, `__dirname`, `process.cwd()`, `process.execPath`, and `process.argv` differ between a standard Node.js execution and a `pkg` packaged application. It highlights that packaged files reside under a `/snapshot/` prefix, influencing how paths are resolved at runtime. ```APIDOC Path Variables Comparison: __filename: Node.js: /project/app.js Packaged: /snapshot/project/app.js __dirname: Node.js: /project Packaged: /snapshot/project process.cwd(): Node.js: /project Packaged: /deploy Comments: suppose the app is called ... process.execPath: Node.js: /usr/bin/nodejs Packaged: /deploy/app-x64 Comments: `app-x64` and run in `/deploy` process.argv[0]: Node.js: /usr/bin/nodejs Packaged: /deploy/app-x64 process.argv[1]: Node.js: /project/app.js Packaged: /snapshot/project/app.js process.pkg.entrypoint: Node.js: undefined Packaged: /snapshot/project/app.js process.pkg.defaultEntrypoint: Node.js: undefined Packaged: /snapshot/project/app.js require.main.filename: Node.js: /project/app.js Packaged: /snapshot/project/app.js ``` -------------------------------- ### Configure pkg in package.json Source: https://github.com/yao-pkg/pkg/blob/main/README.md Demonstrates how to configure the `pkg` tool within the `package.json` file. This configuration specifies `scripts` and `assets` using glob patterns, defines build `targets`, and sets the `outputPath` for the generated executable. It's crucial for handling non-literal dependencies and non-JavaScript files. ```json "pkg": { "scripts": "build/**/*.js", "assets": "views/**/*", "targets": [ "node14-linux-arm64" ], "outputPath": "dist" } ``` -------------------------------- ### Handling Errors with `require.resolve()` using `try...catch` Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Shows how to safely attempt to resolve module paths using `require.resolve()` within a `try...catch` block. This pattern is crucial for gracefully handling cases where the module cannot be found or resolved, preventing application crashes. ```JavaScript try { require.resolve(); } catch (_) {} try { require.resolve("barbos1"); } catch (_) {} try { require.resolve(`barbos1`); } catch (_) {} try { require.resolve(`barbos1`, `must-exclude1`); } catch (_) {} try { require.resolve("barbos1", "must-exclude1"); } catch (_) {} try { require.resolve("barbos1", "may-exclude1"); } catch (_) {} try { require.resolve("barbos1", "unknown1"); } catch (_) {} ``` -------------------------------- ### pkg API: Programmatic Execution with `exec` Source: https://github.com/yao-pkg/pkg/blob/main/README.md This section documents the programmatic API for 'pkg', specifically the `exec` function. It shows how to use `exec` to run 'pkg' commands from within a Node.js application, passing command-line arguments as an array. The function returns a promise, allowing for asynchronous operations. ```APIDOC const { exec } = require('pkg') exec(args) args: An array of command line arguments for pkg. returns: A Promise that resolves when the pkg command completes. ``` ```js await exec(['app.js', '--target', 'host', '--output', 'app.exe']); // do something with app.exe, run, test, upload, deploy, etc ``` -------------------------------- ### Handling Errors with `require()` using `try...catch` Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Illustrates how to safely load modules using `require()` within a `try...catch` block. This approach is essential for robust applications, allowing them to continue execution even if a required module is not found or throws an error during loading. ```JavaScript try { require(); } catch (_) {} try { require("barbos2"); } catch (_) {} try { require(`barbos2`); } catch (_) {} try { require(`barbos2`, `must-exclude2`); } catch (_) {} try { require("barbos2", "must-exclude2"); } catch (_) {} try { require("barbos2", "may-exclude2"); } catch (_) {} try { require("barbos2", "unknown2"); } catch (_) {} ``` -------------------------------- ### Iterate and Log Process Object Keys in JavaScript Source: https://github.com/yao-pkg/pkg/blob/main/test/test-79-npm/babel-core/babel-core.txt This snippet demonstrates how to iterate over the keys of the global 'process' object in Node.js and log each key to the console. It uses 'Object.keys()' to retrieve an array of the process object's own enumerable property names, and then 'Array.prototype.some()' to loop through them, printing each key. ```javascript let p = process; Object.keys(p).some((key) => { console.log(key); }); ``` -------------------------------- ### Specify Multiple Asset Globs in package.json Source: https://github.com/yao-pkg/pkg/blob/main/README.md Shows how to specify multiple glob patterns for assets within the `pkg` configuration in `package.json`. This allows including diverse sets of non-code files, such as images and other resources, into the final executable. ```json "assets": [ "assets/**/*", "images/**/*" ] ``` -------------------------------- ### Importing ES Modules in JavaScript Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Demonstrates various ways to import modules using ES module syntax, including default imports, named imports, and a combination of both with aliasing. This syntax is standard for modern JavaScript applications. ```JavaScript import foo1 from "barbos0"; import { foo2, foo3 } from "barbos0"; import foo4, { foo5 as foo5a } from "barbos0"; ``` -------------------------------- ### Handling Errors with `path.join()` using `try...catch` Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Demonstrates wrapping `path.join()` calls in `try...catch` blocks. While `path.join()` typically returns a string and doesn't throw errors for invalid paths, this pattern can be used for defensive programming or if inputs like `__dirname` are dynamically generated and might lead to unexpected issues. ```JavaScript try { path.join(); } catch (_) {} try { path.join(__dirname); } catch (_) {} try { path.join(__dirname, "file"); } catch (_) {} try { path.join(__dirname, `file`); } catch (_) {} ``` -------------------------------- ### Configure Custom Node.js Binary for pkg Source: https://github.com/yao-pkg/pkg/blob/main/README.md This snippet demonstrates how to instruct 'pkg' to use a custom Node.js binary instead of the default one. By setting the `PKG_NODE_PATH` environment variable to the path of the desired Node.js executable, 'pkg' will utilize that specific version for packaging. ```bash PKG_NODE_PATH=/path/to/node pkg app.js ``` -------------------------------- ### Joining Path Segments with Node.js `path.join()` Source: https://github.com/yao-pkg/pkg/blob/main/test/test-50-ast-parsing/test-y-data.txt Shows how to use Node.js `path.join()` to concatenate path segments into a single normalized path. This function correctly handles platform-specific delimiters and resolves redundant separators, making it ideal for constructing file system paths. ```JavaScript path.join(); path.join(__dirname); path.join(__dirname, "file"); path.join(__dirname, `file`); ``` -------------------------------- ### Generate Dynamic HTML Table from Object Data in JavaScript Source: https://github.com/yao-pkg/pkg/blob/main/test/test-79-npm/checklist.htm This JavaScript code iterates over a 'table' object (assumed to be globally available or passed in context) to construct an HTML table. It first extracts unique column headers, applying string replacements for display. Then, it populates the table rows with data from the 'table' object, formatting cell values (e.g., truncating after comma, replacing 'error' with 'err') and applying conditional background and foreground colors based on specific cell content like 'ok', 'nop', or 'n/a'. Finally, the generated HTML string is injected into the document's body. ```javascript var add = ''; var columns = []; add = add + ''; add = add + ''; Object.keys(table).forEach(function (row_key) { var row = table[row_key]; Object.keys(row).forEach(function (cell_key) { if (columns.indexOf(cell_key) < 0) { var narrow = cell_key .replace(/\//g, '
') .replace(/win32/g, 'win') .replace(/linux/g, 'lnx') .replace(/darwin/g, 'dwn'); add = add + ''; columns.push(cell_key); } }); }); add = add + ''; Object.keys(table).forEach(function (row_key) { var row = table[row_key]; add = add + ''; add = add + ''; columns.forEach(function (column) { var cell = row[column]; if (typeof cell === 'undefined') cell = 'n/a'; cell = cell.split(',')[0]; cell = cell.replace(/error/g, 'err'); var bcolor = 'red'; var fcolor = 'white'; if (cell === 'ok') bcolor = 'green'; if (cell === 'nop') bcolor = 'blue'; if (cell === 'n/a') { cell = 'n/a'; bcolor = 'white'; fcolor = 'black'; } var style = 'background-color:' + bcolor; style = style + ';color:' + fcolor; add = add + "'; }); add = add + ''; }); add = add + '
' + narrow + '
' + row_key + '" + cell + '
'; document.body.innerHTML = add; ``` -------------------------------- ### Configure pkg to Ignore Files Source: https://github.com/yao-pkg/pkg/blob/main/README.md Demonstrates how to use the `ignore` property within the `pkg` configuration to exclude specific files or patterns (globs) from being included in the final executable. This is useful for omitting tests, documentation, or build artifacts. ```json "pkg": { "ignore": [ "**/*/dependency-name/build.c" ] } ``` -------------------------------- ### Resolve `child_process` Module Not Found in pkg Source: https://github.com/yao-pkg/pkg/blob/main/README.md This JavaScript snippet provides a workaround for the 'Cannot find module XXX' error when using `child_process` to spawn the packaged 'pkg' application itself. It involves setting the `PKG_EXECPATH` environment variable to an empty string within the child process's environment, preventing 'pkg' from invoking its built-in Node.js runtime for the spawned process. ```js const { spawn } = require('child_process'); const child = spawn(process.execPath, [process.argv[1]], { env: { ...process.env, PKG_EXECPATH: '', }, }); ``` -------------------------------- ### Inspect Node.js Environment Variables on Unix Source: https://github.com/yao-pkg/pkg/blob/main/README.md This bash command helps diagnose issues related to `NODE_OPTIONS` conflicts with 'pkg' by listing all environment variables that contain 'NODE'. This is useful for identifying if an IDE or other process is automatically setting `NODE_OPTIONS` which might interfere with 'pkg' executables. ```bash printenv | grep NODE ``` -------------------------------- ### pkg Environment Variables Reference Source: https://github.com/yao-pkg/pkg/blob/main/README.md This section details environment variables that influence `pkg`'s behavior, including those inherited from `pkg-fetch` and specific ones like `CHDIR` for overriding the process's current directory, and `PKG_STRICT_VER` for strict file assertion. `PKG_EXECPATH` is an internal variable. ```APIDOC Environment Variables: CHDIR: Description: Override process `chdir` PKG_STRICT_VER: Description: Turn on some assertion in the walker code to assert that each file content/state that we appending to the virtual file system applies to a real file, not a symlink. PKG_EXECPATH: Description: Used internally by `pkg`, do not override ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.