Lance Pollard
Lance Pollard

Reputation: 79420

One liner *NIX command to pipe JSON object keys as arguments to shell command

I would like to have node modules installed only when you are setting up the test environment. The devDependencies and optionalDependencies will still install if you run npm install <the-module>. Instead, I will store these in testDependencies. To do this it would be nice if there was a *NIX one-liner to get the keys from the JSON object, and pipe that into the npm install command. This can be used for travisci and makes it so the default installation doesn't install these extra libraries.

How do you read the package.json file, extract keys to get module names, and run npm install <keys>? The package.json would look pretty much like this:

{
  "name": "the-module",
  "dependencies": {
    "express": "2.x"
  },
  "devDependencies": {
    "ejs": ">= 0.6.1"
  },
  "testDependencies": {
    "mocha": ">= 0.8.1",
    "chai": ">= 0.3.3",
    "sinon": ">= 1.3.1"
  }
}

The command to run would be this:

npm install mocha chai sinon

Trying to do something like this:

npm install $(read-json ./package.json | extract-keys)

Upvotes: 0

Views: 2103

Answers (2)

Andrey Sidorov
Andrey Sidorov

Reputation: 25466

Check JSON.sh

Also, you can make your one-liner shorter by using require('./package.json') directly - it's the same as JSON.parse(require('fs').readFileSync('./package.json', 'utf-8'))

Upvotes: 2

Lance Pollard
Lance Pollard

Reputation: 79420

Figured out a horrible hack :p

npm install $(node -e "console.log(Object.keys(JSON.parse(require('fs').readFileSync('./package.json', 'utf-8'))['testDependencies']).join(' '))")

Still looking for a "correct" way.

Upvotes: 4

Related Questions