Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs: Run a js file on node server startup

I have some piece of nodejs code (scheduler and few db queries) that i want to run each time along with rest of the app (Express App) when the node server is started.
One way which i can think of is creating a batch file which will have 2 lines: one to start the node server and the other to run that node js code (Haven't tested this approach though).

I was thinking if there could be a way to execute that static code via server.js file. I want to run this with in same instance.
Any help here?

like image 392
Prashant soni Avatar asked Aug 16 '26 19:08

Prashant soni


1 Answers

You can execute other scripts in the same directory by adding require() functions to your server.js file:

var exportedThings = require("./path/to/file.js");

In file.js you can assign values to the exports object to export them to requiring scripts:

exports.add = function(first,second){
    return first + second;
}

Now, in server.js you will be able to:

exportedThings.add(1, 5); // Outputs 6
like image 67
metarmask Avatar answered Aug 20 '26 18:08

metarmask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!