Created
November 1, 2024 16:02
-
-
Save peterbean410/58199489e7d22d3eaa4eaaccc4c3300f to your computer and use it in GitHub Desktop.
chid_process.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { spawn } = require('child_process'); | |
// Function to calculate Fibonacci (same as before) | |
function fibonacci(n) { | |
if (n <= 1) { | |
return n; | |
} | |
return fibonacci(n - 1) + fibonacci(n - 2); | |
} | |
// Create a child process | |
const child = spawn('node', ['-e', ` | |
process.stdin.on('data', (data) => { | |
const input = JSON.parse(data.toString()); | |
const result = (${fibonacci})(input.number); | |
console.log(JSON.stringify(result)); | |
}); | |
`]); | |
// Send data to the child process | |
child.stdin.write(JSON.stringify({ number: 5 }) + '\n'); | |
// Handle messages from the child process | |
child.stdout.on('data', (data) => { | |
const result = JSON.parse(data.toString()); | |
console.log(`Result from child process: ${result}`); | |
}); | |
// Handle errors | |
child.stderr.on('data', (data) => { | |
console.error(`Child process error: ${data}`); | |
}); | |
child.on('close', (code) => { | |
console.log(`Child process exited with code ${code}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment