I'm making a Codepen-like app but I want it to support sophisticated JS libraries/frameworks like Vue or Angular 2+ for example. I want to have a live preview of my snippet which updates in a reasonable time. So I came up with an idea that when I create a new snippet I'll initialize a blank starter project on my backend server and run npm start to have Hot reload enabled. When I update the code of my snippet on the frontend side, I'm making a request to the backend server and update files in the starter project which is making the Hot reload refresh the live preview. This is what I got at the moment and it is working.

What I came up with:
This is my function which first copies the starter project to the new location, searches for the free port and eventually spawns npm start:

function createStarter(request, snippetId, callback) {

    const fs = require('fs');
    const path = require('path');
    const portfinder = require('portfinder');
    const { technology } = request.params;

    const snippetPath = path.join(__dirname, '../../static/snippets/vue', snippetId.toString());

    spawnProcess('cp', ['-r', 'vue-starter/', snippetPath], { cwd: snippetPath.slice(0, snippetPath.lastIndexOf('/')) })
        .then(async () => {

            const lastPort = process.env.STARTER_LAST_USED_PORT || 1e4;
            const port = await portfinder.getPortPromise({ port: +lastPort + 1 }).catch(console.error);
            process.env.STARTER_LAST_USED_PORT = port;

            const packageJson = require(`${snippetPath}/package.json`);
            packageJson.scripts.dev += ` --port ${port}`;

            fs.writeFileSync(`${snippetPath}/package.json`, JSON.stringify(packageJson), 'utf8');

            console.log(`Starting project ${snippetId} at port ${port}`);

            spawnProcess('npm', ['start'], { cwd: snippetPath });


where spawnProcess() is just a simple helper which executes spawn(...args) and binds events to the streams.

Actual question:
Is it a good idea to have multiple child processes spawned in parallel? I'm not worried about cp -r from the function above because it's short command and lasts for a few seconds. What I am worried about is npm start which potentially can last for even hours and I'm wondering if this is a good practice to spawn potentially, say, 50 or 100 child processes with npm start running for a long time before it'll be killed. I was thinking about setting a timeout for this command and kill it after about a minute but it can cause another issue which is re-spawning a child process multiple times which requires more resources.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.