-1

I have a pretty big and terribly written piece of code that eventually crashes main Node JS process. Probably there are a lot of memory leaks. I tried fixing it, but it's very bad. (Single letter variables and such.)

Sometimes it crashes in 10 seconds, sometimes after 5 hours, but it crashes.

It is not something mission critical. It is trying to read emails by using IMAP.

I don't want to integrate a queue processor right now. Can I simply create a child instance with Node JS, run this code block in the scope of this? Any correct way of doing it?

Aris
  • 2,978
  • 5
  • 22
  • 31
  • show your code block that you want to run – Sandip Ghosh Jan 18 '18 at 05:34
  • @SandipGhosh Why does it matter? You can imagine any code. It has to run on a separate daemon/instance/whatever. – Aris Jan 18 '18 at 05:40
  • What you are asking about, depends on the kind of code you are trying to execute. You might be able to handle the task simply using promises, instead of child process, or can use pipe if it is about reading and writing streams. – Sandip Ghosh Jan 18 '18 at 05:57
  • @SandipGhosh It is some garbage code that has memory leaks and crashes node after a while. It's not about promises or something. I want to run this code OUT OF main Node process. Think of it like relying on some Queue System, or a cron. – Aris Jan 18 '18 at 06:00
  • Can you add your error , what crashes your node.js ? – Himanshu sharma Jan 18 '18 at 06:22
  • Possible duplicate of [is it possible to achieve multithreading in nodejs?](https://stackoverflow.com/questions/40028377/is-it-possible-to-achieve-multithreading-in-nodejs) – Nidhin David Jan 18 '18 at 07:22

1 Answers1

0

You can use .spawn() or .exec() from the child_process module. If you're running a node.js script, then the program you are running is node and you specify the script you want to run as the first argument and it will run in another process and any other arguments to the script as subsequent arguments.

You just separate out the troublesome code into it's own node.js script and then you can run it this way.

If you want to understand more about the difference between spawn and exec, this is a good article on that.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Why the downvote? Isn't this what the OP is asking for? How to run some of their Javascript in another process? – jfriend00 Jan 18 '18 at 06:09
  • You got my upvote. Do you know how I can pass a port variable though? – Aris Jan 18 '18 at 06:22
  • @Aris - Did you read the doc for `child_process.spawn()`? It shows how to pass either command line arguments or environment variables. Either one could be used to communicate a port number as the script you're running can access either command line arguments or environment variables in `process.argv` or `process.env`. – jfriend00 Jan 18 '18 at 07:13