Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to fork a javascript function in Node.js?

I try to execute a long run function from my main javascript file. I have 2 cpus so how can I just fork a function ?

like image 606
Unitech Avatar asked Jul 18 '12 00:07

Unitech


People also ask

Can you fork in JavaScript?

Yes, there are but using the fork() method handles expensive requests. This is one method that can scale your application server. Other ways include the spawn() , exec() , and execFile() .

Is Node.js better than JavaScript?

As a result, writing JavaScript is incredibly easy, and any working environment is similar to a complete browser. Node. js, on the other hand, only enables the V8 engine. Written JavaScript code, on the other hand, can run in any context, regardless of whether the V8 engine is supported.

Is Node.js basically JavaScript?

Node. js is an open-source, cross-platform JavaScript runtime environment and library for running web applications outside the client's browser. Ryan Dahl developed it in 2009, and its latest iteration, version 15.14, was released in April 2021. Developers use Node.

How do you fork a node?

A Fork Node has one incoming flow and multiple outgoing flows. Create a Fork Node through a Modeler explorer pane or an Activity Diagram: In a Modeler pane, right-click an Activity or Structured Activity Node, point to New, point to Control Node, and then click Fork Node.


2 Answers

Here is node.js documentation on forking and child processes in node.

http://nodejs.org/api/child_process.html

Looks like you might be able to do something like this.

var child = require('child_process').fork('child.js');
child.on("message", function(){});

And you would need the child.js file in this case.

like image 107
earlonrails Avatar answered Oct 10 '22 18:10

earlonrails


For browser-side javascript you would use Web Workers for such a task, the functionality has been ported to NodeJS here Design of Web Workers for NodeJS which wraps child_process API call with the message passing abilities of Web Workers.

like image 22
balupton Avatar answered Oct 10 '22 20:10

balupton