NPM know if script running as a pre/post script

Viewed 495

Let's say I have something like:

{
  "scripts": {
    "clean": "some-clean-script",
    "prebuild": "npm run clean",
    "build": "some-build-script"
  }
}

Inside my some-clean-script (which is written in NodeJS), I want to know if the script is running as part of the prebuild or was called directly.

How do I do that?

1 Answers

There is a variable under env.process called npm_lifecycle_event that stores the key indicating the name of the script in package.json. So in your case, you can just check if process.env.npm_lifecycle_event === 'clean'.

For example, I run the following configuration:

{
  "name": "npm-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "pretest": "node test.js",
    "test": "node index.js", 
    "posttest": "node test.js"
  },
  "author": "",
  "license": "ISC"
}

test.js content:

console.log(process.env.npm_lifecycle_event)

and the output of the command npm test:

> npm-test@1.0.0 pretest /Users/bartlomiejgladys/Desktop/programming/npm-test
> node test.js

pretest

> npm-test@1.0.0 test /Users/bartlomiejgladys/Desktop/programming/npm-test
> node index.js

hi

> npm-test@1.0.0 posttest /Users/bartlomiejgladys/Desktop/programming/npm-test
> node test.js

posttest
Related