'Jenkins CI - how to use pipelines to use a newer version of NodeJS

I am using Jenkins for my continuous integration - I have an Angular 12.x app that when I attempt to build via Jenkins it fails and spits out the following error

Node.js version v10.16.0 detected.
The Angular CLI requires a minimum v12.14.

Please update your Node.js version or visit https://nodejs.org/ for additional instructions.
Build step 'Execute shell' marked build as failure
Finished: FAILURE

I tried to manually update Node.js to run 12.14 as stated however the same error persisted as even though I'd manually updated this via the terminal, Jenkins requires these Node changes to be done via something called 'Pipelines' (as far as I am aware).

Therefore in the Global Tool Configuration I have setup an additional NodeJS 12.4.1 installation which is required for this new pipeline enter image description here

I've then created a new pipeline as follows - this matches up to the same nodejs installation above, and outputs the node and npm versions once I click build to verify it has indeed got the right version.

pipeline {
    agent any
    tools {
        nodejs '12.14.1'
    }
    stages {
        stage('example') {
            steps {
                sh 'node --version'
                sh 'npm --version'
            }
        }
    }
}

enter image description here

My issue is - I am unsure how to connect this pipeline correctly to my existing Jenkins project - the following has been added to remove the existing node modules and re-install them again but it fails and I get a series of errors enter image description here

errors after trying to build

[ignore-test-ng12] $ /bin/sh -xe /tmp/jenkins5815962450175435801.sh
[ignore-test-ng12] $ /var/lib/jenkins/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/12.14.1/bin/node /tmp/jenkins4672532602271656114.js
/tmp/jenkins4672532602271656114.js:1
rm -rf node_modules
       ^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_main_module.js:17:11
Build step 'Execute NodeJS script' marked build as failure
Finished: FAILURE

What am I doing wrong??

-- Expected output --

Build the Angular 12.x application in Jenkins using the NodeJS 12.4.1 installation via the new pipelines setup and marked as 'success' when completed

-- Actual output --

When trying to build this Jenkins spits out errors failing on the first line rm -rf node_modules



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source