Search code examples
javascriptnode.jsfunctionnode-cron

How to Run a Cron Job when the code is in Other File - Node JS


I am trying to execute a cron every 1 hour.

For which I have initiated the cron job in my index.js file as below

const cron = require('node-cron');
const readDocuments = require("./cronJobs/readDocuments");
var task = cron.schedule('0 0 */1 * * *', readDocuments);

task.start();

Where as the actual code to be executed has been written in ./cronJobs/readDocuments and the code inside this file is below, where I am trying to read a csv file.

readDocuments.js

const ResponseManager = require("../common/ResponseManager");

var fs = require('fs');
const csv = require('csv-parser');
console.log('Read Document....')
try {

var filepath = "../files/abc.csv";
fs.createReadStream(filepath)
.on('error', () => {
// handle error
})
.pipe(csv())
.on('data', (row) => {
console.log('rowrowrow',row)
})
.on('end', () => {
// handle end of CSV
})
} catch (error) {
console.log('errorerror',error)
res.status(500).json(ResponseManager(false, error.message));
}

When I run the node js in cmd with node index.js, the console Read Document.... is getting displayed but the other code is not getting executed. It is giving me throw 'execution must be a function'; error

How do I resolve this or what is the actual procedure to execute the code inside a file with cron job from index.js.

Please help. Thanks !!


Solution

  • The second argument to cron.schedule() must be function. You need to wrap the code into a function and export it from the module.

    const ResponseManager = require("../common/ResponseManager");
    const fs = require('fs');
    const csv = require('csv-parser');
    
    module.exports = function () {
      console.log('Read Document....')
      try {
        const filepath = "../files/abc.csv";
        fs.createReadStream(filepath)
          .on('error', () => {
            // handle error
          })
          .pipe(csv())
          .on('data', (row) => {
            console.log('rowrowrow', row)
          })
          .on('end', () => {
            // handle end of CSV
          });
      } catch (error) {
        console.log('errorerror', error)
        res.status(500).json(ResponseManager(false, error.message));
      }
    };