# How to run Cron jobs in Node.js?

To run Cron jobs in Node.js, you can use a Node.js package called `node-cron`. Here are the steps to create and schedule a Node.js script using `node-cron`:

## Install `node-cron`

You can install `node-cron` using the Node Package Manager (npm) with the following command:

```bash
npm install node-cron
```

[info]
## 🔭 Want to get alerted when your Cron doesn’t run correctly?
Go to [Better Stack](https://betterstack.com/uptime/) and start monitoring in 5 minutes.
[/info]

## Create a Node.js script

Create a Node.js script with the code you want to run as a Cron job. For example, let's say you want to delete all temporary files from a directory every day at midnight. You can create a Node.js script called `cleanup.js` with the following code:

```jsx
const fs = require('fs');
const path = require('path');
const cron = require('node-cron');

// Set the directory to clean up
const dirPath = '/path/to/temp/files/';

// Define the Cron job schedule
cron.schedule('0 0 * * *', () => {
  // Get a list of all files in the directory
  fs.readdir(dirPath, (err, files) => {
    if (err) throw err;

    // Delete all files in the directory
    for (const file of files) {
      fs.unlink(path.join(dirPath, file), (err) => {
        if (err) throw err;
      });
    }
  });
});
```

This code uses `node-cron` to define a Cron job that runs every day at midnight. The code inside the Cron job deletes all files in the directory specified by `dirPath`.

## Schedule the Cron job

You can schedule the Cron job by running the Node.js script using the following command:

```jsx
node /path/to/cleanup.js
```

This will start the Cron job and run the code defined in the `cleanup.js` script. The Cron job will continue to run until you stop the Node.js process.

## Verify the Cron job

You can verify that the Cron job is running by checking the output of the Node.js process. You should see output from the `console.log()` statements in the script every time the Cron job runs.

By following these steps, you can create and schedule a Node.js script to run as a Cron job using `node-cron`.

[ad-uptime]