node v8.17.0
version: 1.0.0
fork() is a special case of spawn(), used exclusively to spawn new Node.js processes. These processes are equipped with their own memory stack and V8 engine, therefore they are as well completely decoupled from the parent process. The only way to communicate with the parent process is done via the built-in communication channel.
// Require necessary modules const childProcess = require('child_process'); const fs = require('fs'); // module for accessing file system const got = require('got'); // module for simplified HTTP requests
Change CWD to /tmp, because we only work with temporary data.
try { process.chdir('/tmp'); // This changes CWD to /tmp effectively console.log(`New CWD: ${process.cwd()}`); } catch (e) { console.error(`Setting new CWD failed: ${e.msg || e}`); }
Now download JavaScript file from GitHub Gist and save it for later purposes. URL: Afterwards, fork a child process and let it do its magic.
const fileName = '/tmp/nmea.js'; const resource = ''; // Fetch data from GitHub, write it to disk and fork a child process return got(resource) .then(res => fs.writeFileSync(fileName, res.body)) // Sync. file save - DON'T DO THAT! .then(() => { // Child process is forked const gps = childProcess.fork('/tmp/nmea.js'); // Wait for transmitted data through the communication channel and kill child process. gps.on('message', (data) => { console.log(data); // The data sent from the child process. return gps.kill(); // Kill the child process; its not needed anymore }); // Log message, if child process closed. gps.on('close', (code, msg) => console.log(`Child process closed with status: ${code} - ${msg}`)); return gps; }) .catch(err => console.log(err));

no comments

    sign in to comment