0

I am trying to schedule a function call via setTimeout. The setTimeout call is supposed to run when the module is instantiated. The code that goes inside the callback has nothing to do with the status of the server (port, host, etc...), for example:

fs.readFile(__dirname + "/file.json", "utf-8", (err, data) => {
  if (err) throw err
  // Some fetch operations using data
})

Should I be placing this code directly in the module's file or in the app.listen callback? What are the differences, if there are, between code that goes inside a node.js module directly and code that goes inside the app.listen() callback?

I have already read this post but couldn't find an answer.

Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
  • 1
    We may be able to help you better if you [edit] your question to show us your timeout-handler function. – O. Jones May 19 '21 at 23:02
  • We could answer in more detail if you showed the actual code. Questions here about code can always be answered faster, more accurately and in more specific detail if you show your actual code. In fact, we can often offer solutions you didn't even know to ask about and point out other corrections that could be made to your code or better approaches to the problem. – jfriend00 May 20 '21 at 01:08
  • I added sample code. – Wais Kamal May 20 '21 at 08:35

1 Answers1

1

The difference is in timing - when the code is run.

Things inside the app.listen() callback are executed only AFTER the server has been started and it's initialization has completed (e.g. the server is live). This will always be after all other top level code in the module has been run.

Things at the top level of the module file run when the module is initialized (e.g. first loaded) and may execute before the server is completely live.

The code that goes inside the [setTimeout] callback has nothing to do with the status of the server (port, host, etc...). Should I be placing this code directly in the module's file or in the app.listen callback?

If it has nothing to do with when the server is running, then you can just put it at the top level of the module.

jfriend00
  • 683,504
  • 96
  • 985
  • 979