ใน Node.js, คุณสามารถ execute shell command โดยใช้ child process module ซึ่งมีตัวเลือกให้คุณสามารถทำงานร่วมกับ shell ได้ นี่คือวิธีการทำ:
นำเข้าโมดูล
child_process:ต้องนำเข้าโมดูล
child_processที่มีให้ใน Node.js:1
const { exec } = require('child_process');
ใช้
exec()เพื่อ execute shell command:ใช้ฟังก์ชัน
exec()เพื่อ execute shell command:1
2
3
4
5
6
7
8
9
10
11
12const command = 'ls -l'; // เปลี่ยนเป็นคำสั่ง shell ที่คุณต้องการทดสอบ
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
if (stderr) {
console.error(`Stderr: ${stderr}`);
return;
}
console.log(`Stdout: ${stdout}`);
});commandคือคำสั่ง shell ที่คุณต้องการ execute.errorจะเป็นข้อมูลข้อผิดพลาดหากเกิดข้อผิดพลาดในระหว่างการ execute command.stdoutคือข้อมูลที่รายงานออกมาจาก standard output ของ command.stderrคือข้อมูลที่รายงานออกมาจาก standard error ของ command.
รอผลลัพธ์:
เมื่อคำสั่ง shell ถูก execute เสร็จสิ้น คุณจะได้รับผลลัพธ์ทั้งหมดผ่าน callback function ที่ถูกเรียกเมื่อ command สำเร็จหรือเกิดข้อผิดพลาด.
ตัวอย่างข้างต้นนี้จะแสดงผลลัพธ์จากคำสั่ง shell ls -l ในระบบปฏิบัติการ Unix-like โปรดระวังในการใช้งานคำสั่ง shell ในระบบปฏิบัติการของคุณและควรตรวจสอบค่าผลลัพธ์และการจัดการข้อผิดพลาดตามที่เหมาะสมในแอปพลิเคชันของคุณ.