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.
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
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:
execSync()
option stdio
is configured to prevent logging the returned registry
value to the console./\n$/
is utilized to remove the new line character.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With