[Node.js v8.10.0]
I'm drastically simplifying this example for clarity. I have 3 scripts: parent.js, first.js, and second.js
parent.js:
'use strict';
const path = require('path');
const {fork} = require('child_process');
const firstScript = path.resolve('first.js');
const first = fork(firstScript);
const secondScript = path.resolve('second.js');
const second = fork(secondScript);
first.on('message', message => {
console.log('parent received message from first: ' + message);
second.send(message);
});
second.on('message', message => {
console.log('parent received message from second: ' + message);
});
first.send('original message');
first.js:
'use strict';
class First {
}
process.on('message', async (message) => {
console.log('first received message: ' + message);
process.send(message);
});
module.exports = {First};
second.js:
'use strict';
const {First} = require('./first.js');
process.on('message', message => {
console.log('second received message: ' + message);
process.send(message);
});
Expected output:
first received message: original message
parent received message from first: original message
second received message: original message
parent received message from second: original message
Actual output:
first received message: original message
parent received message first: original message
first received message: original message
second received message: original message
parent received message from second: original message
parent received message from second: original message
In this example, the First class is meaningless. But it illustrates the problem I'm trying to avoid. Specifically, the const {First} = require('./first.js');
line in second.js is wreaking havoc on the IPC (as illustrated by the actual output, compared to the expected output).
Currently, I'm "solving" this problem by moving the First class to a separate file. But I'm wondering if it's possible to keep everything in one file (i.e., still make it possible to export the class in first.js -- but not create IPC-related chaos).