Express.js Mastery / Introduction To Node.js And NPM

package.json and script

🛠️ Custom Scripts with npm run

You can define your own shortcuts using the scripts section.

"scripts": {
  "start": "node index.js",
  "dev": "nodemon app.js"
}

Then run:

npm run dev

💡 This helps you avoid long terminal commands every time.


Creating Custom npm Scripts (with npm run)

Custom scripts let you define shortcuts for repetitive tasks like running your app, testing code, or checking for linting errors.

⚙️ Basic Scripts

Inside your package.json, add a scripts section:

"scripts": {
  "start": "node index.js",
  "dev": "nodemon app.js"
}

You can now run them like this:

npm start       # instead of 'node index.js'
npm run dev     # instead of 'nodemon app.js'

🧪 Testing Script

If you're using Jest, Mocha, or another test runner:

"scripts": {
  "test": "jest"
}

Or for Mocha:


"scripts": {
  "test": "mocha"
}

✅ Run tests with:


npm test

🧼 Linting Script (ESLint)

If you're using ESLint to check code quality:

"scripts": {
  "lint": "eslint ."
}

✅ Run lint check with:

npm run lint

You can also auto-fix issues with:

"scripts": {
  "lint:fix": "eslint . --fix"
}

✅ Auto-fix linting issues:

npm run lint:fix

🎨 Format Code (Prettier)

If you're using Prettier:

"scripts": {
  "format": "prettier --write ."
}

✅ Format all files:

npm run format

Chaining Scripts

You can chain multiple scripts using &&:

"scripts": {
  "check": "npm run lint && npm test"
}

✅ This will run both the linter and test suite:

npm run check

✅ Summary Table

Task

Script

Command

Run app

"start"

npm start

Dev server

"dev"

npm run dev

Run tests

"test"

npm test

Lint check

"lint"

npm run lint

Lint fix

"lint:fix"

npm run lint:fix

Format code

"format"

npm run format

Chain scripts

"check"

npm run check

Sample File

{
  "name": "my-app",
  "version": "1.0.0",
  "description": "Sample package.json with custom npm scripts",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon app.js",
    "test": "jest",
    "lint": "eslint .",
    "lint:fix": "eslint . --fix",
    "format": "prettier --write .",
    "check": "npm run lint && npm test"
  },
  "devDependencies": {
    "nodemon": "^3.0.0",
    "jest": "^29.0.0",
    "eslint": "^9.0.0",
    "prettier": "^3.0.0"
  }
}