10 examples of 'nodejs fork' in JavaScript

Every line of 'nodejs fork' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
13function fork(CLUSTER_ROLE) {
14 cluster.fork({ CLUSTER_ROLE })
15 .on('online', () => {
16 _.dev(() => console.warn(`worker ${CLUSTER_ROLE} is online.`));
17 })
18 .on('exit', (code, signal) => {
19 _.dev(() => console.warn(`Worker ${CLUSTER_ROLE} exited with code ${code} and signal ${signal}.`));
20 fork(CLUSTER_ROLE);
21 });
22}
466function fork(options, workerFunc, thenDo) {
467 // Fork automatically starts a worker and calls `workerFunc`. `workerFunc`
468 // gets as a last paramter a callback, that, when invoked with an error and
469 // result object, ends the worker execution.
470 //
471 // Options are the same as in `create` except for an `args` property that
472 // can be an array of objects. These objects will be passed to `workerFunc`
473 // as arguments.
474 //
475 // Note: `workerFunc` will not be able to capture outside variables (create a
476 // closure).
477 //
478 // Example:
479 // // When running this inside a browser: Note how the UI does not block.
480 // worker.fork({args: [40]},
481 // function(n, thenDo) {
482 // function fib(n) { return n <= 1 ? n : fib(n-1) + fib(n-2); }
483 // thenDo(null, fib(n));
484 // },
485 // function(err, result) { show(err ? err.stack : result); })
486
487 if (!thenDo) { thenDo = workerFunc; workerFunc = options; options = null; }
488 options = options || {};
489 var args = options.args || [];
490 var w = create(options);
491 w.run.apply(w, [workerFunc].concat(args).concat(thenDo));
492 return w;
493}
97fork(modulePath, args, options) {
98 let child;
99 let promise = new Promise((resolve, reject) => {
100 let stdout = '';
101 let stderr = '';
102 child = this.child_process
103 .fork(modulePath, args, options)
104 .on('close', (code, signal) => {
105 if (code !== 0) {
106 const error = new Error('Exited with code ' + code);
107 error.code = code;
108 error.stderr = stderr;
109 error.stdout = stdout;
110 error.signal = signal;
111 reject(error);
112 } else {
113 resolve({
114 code: code,
115 signal: signal,
116 stderr: stderr,
117 stdout: stdout
118 });
119 }
120 })
121 .on('error', (error) => {
122 error.stdout = stdout;
123 error.stderr = stderr;
124 reject(error);
125 });
126
127 if (child.stdout) {
128 child.stdout
129 .setEncoding('utf8')
130 .on('data', (data) => {
131 stdout += data;
132 });
133 }
134 if (child.stderr) {
135 child.stderr
136 .setEncoding('utf8')
137 .on('data', (data) => {
138 stderr += data;
139 });
140 }
141 });
142 promise.child = child;
143 return promise;
144}
34function forkProcess() {
35 const nodeProcess = this.nodeProcess || process;
36 const cluster = this.cluster || clusterModule;
37 const onlineEventHandlerFunc = onlineEventHandler.bind(this);
38 const exitEventHandlerFunc = exitEventHandler.bind(this, cluster);
39 return new Promise((resolve, reject) => {
40 try {
41 if (this.settings.application.cluster_process) {
42 if (cluster.isMaster) {
43 this.config.process.isMaster = true;
44 const numWorkers = this.settings.application.number_of_clusters || os.cpus().length;
45 this.logger.info(`Master cluster setting up ${numWorkers} workers...`);
46 for (let i = 0; i < numWorkers; i++) {
47 const worker = cluster.fork();
48 }
49 for (const id in cluster.workers) {
50 // Receive messages from this worker and handle them in the master process.
51 cluster.workers[ id ].on('message', workerProcessMessageHandler.bind(this));
52 }
53
54 cluster.on('online', onlineEventHandlerFunc);
55 cluster.on('exit', exitEventHandlerFunc);
56 // this.config.process.isClustered = true;
57 reject(new Error('Leave Promise Chain: Forking Process'));
58 } else {
59 this.config.process.pid = nodeProcess.pid;
60 this.config.process.isClustered = true;
61 this.config.process.isMaster = false;
62 this.status.emit('cluster-process-waiting-on-master', true);
63 nodeProcess.send({
64 cmd: 'requestMasterProcessId',
65 pid: process.pid,
66 });
67 nodeProcess.on('message', (msg) => {
68 this.status.emit('cluster-process-master-message', msg);
69 this.status.emit('clustered-process-master-process-id', msg.masterProcessId);
70 this.config.process.masterProcessId = msg.masterProcessId;
71 // console.log(`WORKER (${process.pid}): Got message`, msg);
72 });
73
74 resolve(true);
75 }
76 } else {
77 this.config.process.isClustered = false;
78 resolve(true);
79 }
80 } catch (e) {
81 reject(e);
82 }
83 });
84}
23fork(workerModule: string) {
24 const filteredArgs = process.execArgv.filter(
25 v => !/^--(debug|inspect)/.test(v)
26 );
27
28 const options: cp.ForkOptions = {
29 execArgv: filteredArgs,
30 env: process.env,
31 cwd: process.cwd()
32 };
33
34 const args = ['--start-worker'];
35
36 this.childProcess = cp.fork(workerModule, args, options);
37
38 this.childProcess.on('message', this.receiveFromWorker.bind(this));
39
40 this.childProcess.once('exit', code => {
41 this.exitCode = code;
42 this.emit('exit', code);
43 });
44
45 this.childProcess.on('error', err => {
46 this.emit('error', err);
47 });
48}
14function fork(offset, execArgv) {
15 if (execArgv)
16 cluster.setupMaster({execArgv});
17
18 const check = common.mustCall(checkExitCode);
19 cluster.fork({portSet: debuggerPort + offset}).on('exit', check);
20}
77export function forkP(
78 moduleName: string, args?: string[], options?: ForkOptions,
79 log?: (text: string) => void): Promise {
80 const stringifiedCommand =
81 `\`${moduleName}${args ? (' ' + args.join(' ')) : ''}\``;
82 if (log) {
83 log(`> Running: ${stringifiedCommand}`);
84 }
85 return promisifyChildProcess(
86 fork(moduleName, args, Object.assign({stdio: 'inherit'}, options)));
87}
104function forkWorker() {
105
106 var worker = cluster.fork();
107
108 worker.on('message', function (msg) {
109
110 if (msg.cmd) {
111
112 if (msg.cmd == 'workerStarted') {
113
114 runningWorkers++;
115
116 if (runningWorkers === parseInt(totalWorkers)) {
117 console.log("Calipso configured for: ".green + (global.process.env.NODE_ENV || 'development') + " environment.".green);
118 console.log("Calipso server running ".green + runningWorkers + " workers, listening on port: ".green + port);
119 }
120
121 }
122
123 }
124
125 });
126
127}
18forkWorker() {
19 const worker = new Worker({
20 modulePath: this.modulePath,
21 workerOptions: this.workerOptions,
22 });
23
24 this.stdout.add(worker.child.stdout);
25 this.stderr.add(worker.child.stderr);
26
27 this.workers.push(worker);
28
29 return worker;
30}
48function forkWorker(i) {
49 var worker = cluster.fork({
50 PARSER_URL: parsers[i]
51 });
52 worker.on("exit", function() {
53 console.log("Worker crashed! Spawning a replacement of worker %s", worker.id);
54 forkWorker(i);
55 });
56}

Related snippets