How to run Cron jobs in Node.js?

Better Stack Team
Updated on May 26, 2023

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:

npm install node-cron

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:

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:

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.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack