DEV Community

Ajit Forger
Ajit Forger

Posted on • Updated on

Useful NPM scripts, Example usage(Basics Node.js Series)

Hi hello world, In this micro article we'll explore some essential NPM scripts that will help you kickstart your Node.js journey

As you embark on your journey to master Node.js

Managing your project, dependencies, and automating common tasks is an essential part of the process

NPM scripts are the initial and fundamental step to mastering Node.js, enabling you to streamline your development workflow and make your projects more efficient

Image description

An intro to the Npm scripts

  • Npm scripts in Node.js are a powerful and convenient way to automate various tasks
  • They are defined in "package.json" file under "scripts"

These scripts allow you to run a common development and build tasks with simple commands.

Example script definitions

"scripts": {
  "start": "node app.js",
  "test": "mocha test/*.js",
  "build": "webpack"
}
Enter fullscreen mode Exit fullscreen mode

Here are some examples of useful NPM scripts you can include in your package.json file

1. Start your application

You can start your application by using npm start here's a basic example of how to start a script

"scripts": {
  "start": "node server.js"
}
Enter fullscreen mode Exit fullscreen mode

2. Auto reloading with nodemon

Development server like Express.js and want it to restart whenever you make changes

"scripts": {
  "dev": "nodemon server.js"
}
Enter fullscreen mode Exit fullscreen mode

3. Running tests

Testing framework like Mocha, you can set up a script for running tests.

"scripts": {
  "test": "mocha"
}
Enter fullscreen mode Exit fullscreen mode

4. Linting our code

Using a linter like ESLint, you can create a script for code linting.

"scripts": {
  "lint": "eslint ."
}
Enter fullscreen mode Exit fullscreen mode

5. Building your project(eg. webpack/babel)

Project requires a build step, such as transpiling or bundling, you can create a script for that (if needed)

"scripts": {
  "build": "webpack"
}
Enter fullscreen mode Exit fullscreen mode

6. Running a custom task

You can define custom scripts for specific tasks, such as data migrations, or generating documentation

"scripts": {
  "migrate": "node db-migration.js",
  "generate-docs": "jsdoc --configure .jsdoc.json"
}
Enter fullscreen mode Exit fullscreen mode

7. Run multiple scripts

At some point we might need to be run a multiple scripts, for that, use the concurrently package to run multiple scripts simultaneously.

"scripts": {
  "dev": "concurrently \"npm run server\" \"npm run client\"",
  "server": "nodemon server.js",
  "client": "webpack --watch"
}
Enter fullscreen mode Exit fullscreen mode

8. Clean the build directory

If you have a build directory that you want to clean before rebuilding

"scripts": {
  "clean": "rm -rf dist",
  "build": "npm run clean && webpack"
}
Enter fullscreen mode Exit fullscreen mode

Use npm run clean to remove the "dist" directory before running the build script.

Bouns (example script)

Custom report generation

If you need to generate custom reports or exports, you can create a script for that

// generate-report.js
const reportGenerator = require('./report-generator');

reportGenerator.generateReport()
    .then(() => {
        console.log('Report generated successfully.');
        process.exit(0);
    })
    .catch((error) => {
        console.error('Report generation failed:', error);
        process.exit(1);
    });
Enter fullscreen mode Exit fullscreen mode

Calling the file

"scripts": {
   "generate-report": "node generate-report.js"
}
Enter fullscreen mode Exit fullscreen mode

npm generate-report, command to run the script


Another Example (useful script), Currency converter

Get exchange rates using exchangeratesapi and using npm custom scripts to get exchange rates on command line

  • Create a new JavaScript file named currencyConverter.js
  • Install the axios package to make HTTP requests
  • Create an account on https://exchangeratesapi.io/ and replace the apikey
const axios = require("axios");

async function convertCurrency(amount, fromCurrency, toCurrency) {
  try {
    const response = await axios.get(
      `https://api.apilayer.com/exchangerates_data/latest?base=${fromCurrency}&symbols=${toCurrency}`,
      {
        headers: {
          Authorization: "Bearer [YOUR_API_KEY]",
        },
      }
    );

    const conversionRate = response.data.rates[toCurrency];
    if (!conversionRate) {
      console.log(
        `Currency conversion from ${fromCurrency} to ${toCurrency} is not supported.`
      );
      return;
    }

    const convertedAmount = amount * conversionRate;
    console.log(
      `${amount} ${fromCurrency} is equivalent to ${convertedAmount} ${toCurrency}`
    );
  } catch (error) {
    console.error("Error fetching exchange rates:", error.message);
  }
}

const args = process.argv.slice(2);
if (args.length !== 3) {
  console.log(
    "Usage: node currencyConverter.js <amount> <fromCurrency> <toCurrency>"
  );
  process.exit(1);
}

const amount = parseFloat(args[0]);
const fromCurrency = args[1].toUpperCase();
const toCurrency = args[2].toUpperCase();

convertCurrency(amount, fromCurrency, toCurrency);

Enter fullscreen mode Exit fullscreen mode

In your package.json, add the script

"scripts": {
   "currency-convert": "node currencyConverter.js"
}
Enter fullscreen mode Exit fullscreen mode

Now, you can run the currency conversion script using the npm run currency-convert

npm run currency-convert 560 INR USD

Conclusion

Now that you've dipped your toes into the whimsical world of NPM scripts, Stay tuned for more advanced articles where we'll explore the depths of Node.js

If you have any queries or just want to share your Node.js anecdotes, and command below

happy coding! 🚀🐉💻

Top comments (0)