Dark mode
Child Process Module
เหตุผลที่ควรเรียนรู้ child_process
บางครั้ง CLI tool ต้องสั่งโปรแกรมอื่น เช่น รัน git, เปิดไฟล์, หรือประมวลผลงานหนัก ๆ ที่ไม่ควรทำใน process หลัก child_process ช่วยให้ Node.js สั่งงานระบบปฏิบัติการหรือโปรแกรมอื่นได้อย่างปลอดภัยและยืดหยุ่น
- ถ้าต้องการให้ CLI ของคุณสั่ง build, test, หรือรัน shell command ต้องใช้ child_process
- ใช้สำหรับงานที่ Node.js ทำเองไม่ได้ เช่น แปลงไฟล์, สั่งโปรแกรมภายนอก
- มือใหม่จะเข้าใจการรันโปรแกรมแบบ automation และ scripting มากขึ้น
แนะนำ Child Process module
child_process
ใช้สำหรับรันคำสั่ง shell หรือโปรแกรมอื่น ๆ จาก Node.js เช่น สั่ง git, เปิดโปรแกรม, ประมวลผลงานหนักแยก process สามารถสื่อสารกับ process ลูกได้
การรันคำสั่ง shell แบบง่าย
exec(command[, options], callback)
รันคำสั่ง shell และรับผลลัพธ์ทั้งหมดเป็น string
js
const { exec } = require("child_process");
exec("ls -l", (err, stdout, stderr) => {
if (err) return console.error(err);
console.log(stdout);
});
การรัน process แบบ stream
spawn(command[, args][, options])
เหมาะสำหรับรับผลลัพธ์ทีละ chunk หรือรัน process ที่ output เยอะ
js
const { spawn } = require("child_process");
const child = spawn("node", ["-v"]);
child.stdout.on("data", data => console.log(`stdout: ${data}`));
การสื่อสารกับ process ลูก (stdin/stdout)
js
const { spawn } = require("child_process");
const child = spawn("cat");
child.stdin.write("hello\n");
child.stdin.end();
child.stdout.on("data", data => console.log("OUT:", data.toString()));
เคล็ดลับและกรณีใช้งานจริง
- สั่ง build/test จาก CLI tool
- รัน shell script อัตโนมัติ
- ใช้ spawn สำหรับ process ที่ output เยอะหรือ interactive
ตัวอย่าง: รันคำสั่ง git จาก Node.js
js
const { exec } = require("child_process");
exec("git status", (err, stdout) => {
if (err) return;
console.log(stdout);
});