Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read npm config values from within a Node.js script

Tags:

node.js

npm

Within Node.js, I would like to read the value of the registry property that npm uses to determine where to download packages.

const registry = someApi.get('registry');

I want to know so that I can create a preinstall script that ensures developers are downloading packages through the local Artifactory instance rather than directly from npm.org.

const EXPECTED_REGISTRY = 'https://example.com/artifactory'
const registry = someApi.get('registry'); 
if (registry !== EXPECTED_REGISTRY) {
   console.log('Please configure your .npmrc to use Artifactory');
   console.log('See http://example.com/instructions');
   process.exit(1);
}

One way to do it would be to shell out to npm config list --json. There must be an API that will give me the same result. I'm just having trouble finding it.

like image 448
Patrick McElhaney Avatar asked Jan 08 '18 21:01

Patrick McElhaney


2 Answers

While there's already an accepted answer, I'll post an alternative answer for posterity.

If you run your script using the npm command and a script added to the scripts property of your package.json file, then your NPM config properties should be accessible to your NodeJS script via the pattern process.env.npm_config_*.

For example, given this package.json file:

{
  "scripts": {
    "start": "node -p \"process.env.npm_config_foo\""
  }
}

When the following commands are run:

npm config set foo bar
npm start

The output is:

> @ start /Users/anonymous/projects/my-package
> node -p "process.env.npm_config_foo"

bar

Note that if your scripts property is not one of NPM's well-known properties (e.g. test, start), you'll need to use npm run <script-name> instead of npm <script-name>.

Reference: https://docs.npmjs.com/misc/config

like image 161
Dan Mork Avatar answered Sep 24 '22 14:09

Dan Mork


I'm quite certain you'll have to "shell out", there's no other API that I'm aware of.

You can utilize nodes execSync() or exec() methods to execute the npm config sub-command get, i.e:

$ npm config get registry

Node example using execSync():

const execSync = require('child_process').execSync;

const EXPECTED_REGISTRY = 'https://example.com/artifactory';
const registry = execSync('npm config get registry',
    { stdio: ['ignore', 'pipe', 'pipe'] }).toString().replace(/\n$/, '');

if (registry !== EXPECTED_REGISTRY) {
  console.log('Please configure your .npmrc to use Artifactory');
  console.log('See http://example.com/instructions');
  process.exit(1);
}

Notes:

  1. The execSync() option stdio is configured to prevent logging the returned registry value to the console.
  2. The regex /\n$/ is utilized to remove the new line character.
like image 28
RobC Avatar answered Sep 22 '22 14:09

RobC