Useful NPM scripts, Example usage(Basics Node.js Series)
Tags: webdev, javascript, beginners, node
Published: 2023-10-30 12:32:42

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p8kggc8ksbfkjn9z2oz4.gif)

**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**

```json
"scripts": {
  "start": "node app.js",
  "test": "mocha test/*.js",
  "build": "webpack"
}
```

---


## **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


```json
"scripts": {
  "start": "node server.js"
}
```

**2. Auto reloading  with nodemon**

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

```json
"scripts": {
  "dev": "nodemon server.js"
}
```

**3. Running tests**

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

```json
"scripts": {
  "test": "mocha"
}
```

**4. Linting our code**

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

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

**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)

```json
"scripts": {
  "build": "webpack"
}
```

**6. Running a custom task**

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

```json
"scripts": {
  "migrate": "node db-migration.js",
  "generate-docs": "jsdoc --configure .jsdoc.json"
}
```

**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.

```json
"scripts": {
  "dev": "concurrently \"npm run server\" \"npm run client\"",
  "server": "nodemon server.js",
  "client": "webpack --watch"
}
```

**8. Clean the build directory**

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

```json
"scripts": {
  "clean": "rm -rf dist",
  "build": "npm run clean && webpack"
}
```

> 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

```javascript
// 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);
    });
```

**Calling the file**

```json
"scripts": {
   "generate-report": "node generate-report.js"
}
```

_**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`

```Javascript
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);

```

In your `package.json`, add the script 

```json
"scripts": {
   "currency-convert": "node currencyConverter.js"
}
```

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! 🚀🐉💻