Search code examples
javascriptnode.jsexpressnode-cron

Making variable accessible to other node modules


I have a node script that also doubles as an express server. It's purpose is to run cron jobs, but I would like to be able to see the last time a job ran by making a request to an express route.

The entry point index.js:

require('@babel/register')({

})
import cron from 'node-cron';
import { test } from 'Tasks';

let task = cron.schedule('* * * * *', () =>{
  task.lastruntime = new Date();
  ....
})

require('./server.js')

server.js

import express from 'express';
import bodyParser from 'body-parser';
import http from 'http';

const app = express();

let routes = require('./routes');
app.use(routes);

http.createServer(app).listen(7777, () => console.log("Listening on port 7777!"));

and the routes.js

let router = require('express').Router();
router.get("/test", () => console.log('test'));

module.exports = router;

I would like to make task from index.js available to routes.js so that I can check its status but I'm really not sure how to go about it. If I put it in it's own module and imported it into the index to start the task, and then import it again in routes to check it's status, I would have two different instances of task that would both be running, which is not what I want to accomplish.


Solution

  • Just export and import :

    task.js

    export let task = cron.schedule('* * * * *', () =>{
      task.lastruntime = new Date();
      ....
    })
    

    route.js and index.js

    import { task } from './task.js';