Packaging Node.js functions created from scratch¶
FunctionGraph supports packaging Node.js functions as zip files.
This packaging method is suitable for both event and HTTP functions created from scratch.
To package your Node.js function as a zip file, you can use npm scripts to automate the packaging process.
To do so adapt your package.json file to include a postpack script that creates a zip file containing your function code and its dependencies.
Then you can use the
npm pack
command to create a tarball of your package, which will trigger the postpack script to create the zip file.
Package.json¶
Adapt your package.json file to include the necessary scripts and dependencies for packaging your Node.js function as a zip file.
{
...
"scripts": {
"postpack": ".\postpack.cmd", // for Windows
"postpack": "bash ./postpack.sh" // for Linux
},
"dependencies": {
// add here dependencies of your function
},
"devDependencies": {
// add here dev dependencies of your function
},
"bundleDependencies": [
// add here bundle dependencies if needed
// these are dependencies from "dependencies" that will be included in the zip package
],
"files": [
// add here files to be included in the bundle, e.g.:
"*.js",
"src/**/*",
"bootstrap" // for http functions
]
...
}
Next to the files included in the “files” section of your package.json, the package will also contain “README.md”, “package*.json”, and “node_modules” folder with the dependencies specified in “bundleDependencies”.
For details, see package.json documentation.
Postpack script for Linux¶
Copy following file content to a file named postpack.sh in the same folder as your package.json and make it executable.
#!/bin/bash
# Postpack script to create a zip file from the npm package tarball
# This script is intended to be run on Linux using bash.
# It extracts the contents of the npm package tarball, creates a zip file from it,
# and then cleans up the tarball.
echo "Running postpack script for Linux"
rm -f ${npm_package_name}-${npm_package_version}.zip
tarball=${npm_package_name}-${npm_package_version}.tgz
tar -tf $tarball | sed 's/^package\///' | zip -@r ${npm_package_name}-${npm_package_version}.zip
rm $tarball
To make it executable run following command in the terminal:
chmod +x postpack.sh
Postpack script for Windows¶
Copy following file content to a file named postpack.cmd in the same folder as your package.json
@echo off
setlocal
echo "Running postpack script for Windows"
if exist dist rmdir /s /q dist
mkdir dist
tar -x -z -f "%npm_package_name%-%npm_package_version%.tgz" -C dist --strip-components=1
tar -c -a -f "%npm_package_name%-%npm_package_version%.zip" -C dist *
if exist "%npm_package_name%-%npm_package_version%.tgz" del /f /q "%npm_package_name%-%npm_package_version%.tgz"
if exist dist rmdir /s /q dist
endlocal