How to open command prompt in Nodejs

PHPz
Release: 2023-05-23 21:03:37
Original
594 people have browsed it

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');
Copy after login

Then, where you want to open the command prompt, execute the spawn method:

const cmd = spawn('cmd');
Copy after login

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']);
Copy after login

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 ');
Copy after login

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();
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!