How to correctly pass environment variables from GitHub Actions to a Node.js script?

I’m having trouble with my Angular app. I want to include a build number in my env config file. I made a Node.js script to write this number before the build step. Here’s what my GitHub Actions workflow looks like:

run: |
  npm install
  node update-build-number.js build=${{ env.GITHUB_ACTION }}
  npm run build-demo

The script works fine when I test it alone. It also runs in Actions. But after building and deploying, the build number shows up as undefined.

I’ve looked at other solutions, like writing the variable to a file and then reading it with Node. But that seems messy.

Does anyone know a clean way to pass environment variables from GitHub Actions to a Node.js script? I’m stumped and could use some help!

I’ve encountered this issue before, and here’s a solution that’s worked well for me. Instead of passing the build number as a command-line argument, you can use GitHub Actions’ built-in environment variables directly in your Node.js script.

Modify your workflow file to set the build number as an environment variable:

env:
  BUILD_NUMBER: ${{ github.run_number }}

run: |
  npm install
  node update-build-number.js
  npm run build-demo

Then in your Node.js script, access it using process.env:

const buildNumber = process.env.BUILD_NUMBER;

This approach is more straightforward and less error-prone. It also keeps your workflow file cleaner. Just ensure your script handles cases where the variable might be undefined. This method has been reliable in my projects, and it should solve your issue with the undefined build number.

I’ve dealt with similar issues before, and it can be frustrating. One approach that worked well for me was using the process.env object in Node.js to access environment variables directly. Instead of passing the build number as a command-line argument, you could set it as an environment variable in your workflow:

- name: Set Build Number
  run: echo "BUILD_NUMBER=${{ github.run_number }}" >> $GITHUB_ENV

- name: Build and Deploy
  run: |
    npm install
    node update-build-number.js
    npm run build-demo

Then in your Node.js script, you can access it like this:

const buildNumber = process.env.BUILD_NUMBER;

This method is cleaner and more reliable in my experience. It also allows you to set multiple variables easily if needed. Just remember to add error handling in case the variable isn’t set for some reason. Hope this helps!