We sometimes don't want to pollute our local machine by installing Node if we don't use it often. In this scenario we can run a desired version of Node via Docker container:
docker run --rm \
node:16-alpine \
sh -c "node --version"
Output:
v16.20.2
Running npm
The above also means that we can use Node tools against our local Node application repository, without the need to install Node locally:
docker run --rm \
-v "$PWD":/app \
-w /app \
node:16-alpine \
sh -c "npm install && npm audit"
The above command should be run from the project's root directory.
If package.json lists some dependencies from a private package hosted on GitHub Packages e.g.:
"dependencies": {
...
"@foo/bar": "^0.5.4",
...
}
...and inside Docker there is no GitHub token, npm install might throw this error if npm can't be authenticated against GitHub:
npm ERR! 401 Unauthorized - GET https://npm.pkg.github.com/download/@foo/bar/0.5.4/db46279e9b10a74cec83b15ac06422c479e4d193fd3c8366c839ace085244c9b - authentication token not provided
This token is GitHub Personal Access Token (PAT) and it should have a permission to read our private npm package.
If our local machine is authenticating via GitHub CLI (gh) we can run:
gh auth token
Output is PAT that npm can use and it will be in this format:
ghp_xxx...
We can store this value in the local env variable:
export NODE_AUTH_TOKEN=$(gh auth token)
We now need to create a local .npmrc file which contains authentication
echo "@foo:registry=https://npm.pkg.github.com/" > .npmrc
echo "//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}" >> .npmrc
...so .npmrc file will look like this:
@foo:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=ghp_aAT3B3N...iiOO
If we try to execute npm install again, the issue with missing token should be resolved now.
Running Prettier
If prettier is added as devDependency in NodeJS project and .prettierrc config file is provided we can run prettier from Node Docker container, with no need to install Node on the local machine:
To find style errors:
docker run --rm \
-v "$PWD":/app \
-w /app \
node:18-alpine \
sh -c "npm install && npx prettier --ignore-path .gitignore --check '**/*.+(ts|js|json|yml)'"
To fix the reported style errors:
docker run --rm \
-v "$PWD":/app \
-w /app \
node:18-alpine \
sh -c "npm install && npx prettier --ignore-path .gitignore --write '**/*.+(ts|js|json|yml)'"
Running yarn
Node Docker image comes with yarn installed so we can use it just as we used npm:
docker run --rm \
-v "$PWD":/app \
-w /app \
node:18-alpine \
sh -c "yarn install --frozen-lockfile && yarn audit --audit-level=critical"
---








