Skip to the content.

Oubliette - a programmatic interface for npm

NPM version Node.js CI Code Climate Test Coverage Discover zUnit

The official API was removed from npm in v8.0.0. Since then the only option for using npm from NodeJs is by executing the npm binary. This module wraps the exec call within convenient asynchronous and synchronous APIs.

Usage

Asynchronous API

const { asyncApi: npm } = require('oubliette');

Synchronous API

const { syncApi: npm } = require('oubliette');

Execute a command without arguments

npm().install();

Execute a command with arguments

npm().install('express', 'pg', 'debug');

Execute command with short options

npm().install('nodemon', { 'g': true });

Execute a command with long options

npm().install('nodemon', { 'global': true, 'install-strategy': 'shallow' });

Execute a command with hyphens

npm()['find-dupes']();
// or
npm().findDupes();

Parsing Output

Oubliette uses NodeJS child_process.execSync and child_process.exec under the hood. These sometimes return stdout as a Buffer instead of as a String. Oubliette ensures string conversion by default.

const output = npm().view('express');

This is inconvenient if you want JSON output for commands that support the --json option, so you can specify a format function.

const { syncApi: npm, formats: { jsonFormat: format } } = require('oubliette');
const { version } = npm({ format }).view('express', { json: true });

You can also receive the output as a Buffer.

const { syncApi: npm, formats: { bufferFormat: format } } = require('oubliette');
const buffer = npm({ format }).view('express', { json: true });

Finally you can receive the raw output.

const { syncApi: npm, formats: { rawFormat: format } } = require('oubliette');
const output = npm({ format }).view('express', { json: true });

Child Process Options

You can specify any of the child_process.execSync and child_process.exec options…

const options = { cwd: __dirname };
await npm({ options }).exec('-c', 'pwd');

Error Handling

Handle errors by wrapping the npm command in a try/catch.

try {
  const output = await npm().view('express', 'version', { json: true });
} catch (err) {
  console.error(err);
}

The error will be decorated with stdout and stderr properties.

Why “Oubliette”?

According to Wikipedia, an oubliette is a basement room or bottle dungeon which is accessible only from a hole in a high ceiling and therefore difficult to escape from. If you’ve ever descended into the npm souce code you will appreciate the similarity!