Home > Article > Web Front-end > How to open command prompt in Nodejs
In Node.js, you can open the command prompt through the spawn method of the child_process module.
First, you need to introduce the child_process module into the code:
const { spawn } = require('child_process');
Then, where you want to open the command prompt, execute the spawn method:
const cmd = spawn('cmd');
This will be the current Open a command prompt window at the location. If you want to open the command prompt at a specific location, you can pass a specific path in the spawn method:
const cmd = spawn('cmd', ['/k', 'cd', 'C:/Users/Username/Path']);
This will open the command prompt at the location "C:/Users/Username/Path".
In the command prompt that opens, you can execute any supported command. For example, you can list the files and directories of the current directory:
cmd.stdin.write('dir ');
This will execute the "dir" command in the command prompt and output the results.
When the command prompt is not needed, you can use the following code to close it:
cmd.stdin.end();
Complete code example:
const { spawn } = require('child_process'); const cmd = spawn('cmd', ['/k', 'cd', 'C:/Users/Username/Path']); cmd.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); cmd.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); cmd.on('close', (code) => { console.log(`child process exited with code ${code}`); }); cmd.stdin.write('dir '); cmd.stdin.end();
The above code will be in "C:/Users/ Open the command prompt under the "Username/Path" location and execute the "dir" command to output the results to the console. When the command prompt is closed, the subprocess exit code will be output.
The above is the detailed content of How to open command prompt in Nodejs. For more information, please follow other related articles on the PHP Chinese website!