Search code examples
javascriptnode.jsrequirechild-process

JS - Require & child-process


I wanted to make a command from my code so I created a js file and started testing. I only want to do a "dir" (ls but on windows). I have this in my functions.js:

window.setInterval(function(){
    const { exec } = require('node:child_process');
    exec('"dir"', (stdout, stderr, err)=>{
        console.log(stdout, stderr, err)
    });
}, 1000);

But it didn't work and I have this error popping up:

Uncaught Error: Module name "node:child_process" has not been loaded yet for context: _. Use require([]) https://requirejs.org/docs/errors.html#notloaded

I think I'm understanding why this isn't working but I don't know how to make it work. Can somebody explain it to me please?

EDIT

I still have this problem but I'm going forward... Now, in my console I have: 'Échec du chargement pour le module dont la source est « node:child_process ».'

while my code is :

import { exec } from 'node:child_process';

And my function looks like this:

let first = true;
const timer = 60000;    //in milliseconds

/**
 * Make a command prompt and write in it the command for checking if there are sessions which need to be deleted.
*/
function deleteOverSessions(){
    console.log(first);
    exec('echo %cd%');
    if(first){
        exec('cd ../../..');
        first = false;
    }

    exec('symfony console session:check-and-delete-finished-ones', (error, stdout, stderr) => {
        if (error) {
            console.error(`error: ${error.message}`);
            return;
        }
    
        if (stderr) {
            console.error(`stderr: ${stderr}`);
            return;
        }

        console.log(`stdout:\n${stdout}`);
    });  
}

PS: It works if I start the script in a terminal but not if I launch the page in a browser

Does somebody know how to solve this problem?


Solution

  • You are confusing the require function provided by Require.js with the require function provided in CommonJS modules for Node.js.

    While they are both tools for loading modules, they are tools for loading different kinds of modules.

    The node:child_process module is built into Node.js and is not available in web browsers (which, for hopefully obvious security reasons, have no features for running arbitrary executables on the user's computer!)