0

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.

SpeedOfRound
  • 1,210
  • 11
  • 26
  • What about declaring and exporting it without initializing it and than only initializing it in index.js? This way you'll have the right reference in routes.js – Shachar Har-Shuv May 03 '19 at 15:49
  • @ShacharHar-Shuv I don't understand, how do I get the reference to routes? – SpeedOfRound May 03 '19 at 15:50
  • 1
    Your problem was that importing from a module twice, actually initialize the variable twice. But if you just declare the variable (or else, create an object to hold it), than you can initialize it in index.js, and assign it to the "shared object". This object will hold the reference of the "task" object, which was initialized only once. – Shachar Har-Shuv May 03 '19 at 15:55

1 Answers1

1

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';