Node
nodejs child process
한츄
2024. 10. 4. 09:12
Node.js 자식 프로세스(Child Process): 알아야 할 모든 것 (freecodecamp.org)
Node.js 자식 프로세스(Child Process): 알아야 할 모든 것
spawn(), exec(), execFile(), fork() 사용법 > 업데이트: 이 글은 현재 필자의 책 "Node.js Beyond The Basics"의 일부입니다. > jscomplete.com/node-beyond-basics [https://github.com/samerbuna/efficient-node] 에서 Node에 대한 더 많은
www.freecodecamp.org
1. spawn()
- 용도: 새로운 프로세스를 생성하고, 표준 입력/출력 스트림을 통해 데이터 전송.
- 특징:
- 비동기적으로 작동하며, 데이터 스트림을 처리할 수 있음.
- 대용량 데이터 전송에 유리.
- 사용 예:
const { spawn } = require('child_process'); const child = spawn('ls', ['-lh', '/usr']); child.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); child.stderr.on('data', (data) => { console.error(`stderr: ${data}`); }); child.on('close', (code) => { console.log(`자식 프로세스가 ${code} 코드로 종료됨`); });
2. exec()
- 용도: 쉘 명령어를 실행하고, 결과를 콜백 함수로 반환.
- 특징:
- 명령어의 실행 결과를 버퍼에 저장하여 한 번에 반환.
- 짧고 간단한 명령어 실행에 적합.
- 결과의 크기에 제한이 있음.
- 사용 예:
const { exec } = require('child_process'); exec('ls -lh /usr', (error, stdout, stderr) => { if (error) { console.error(`오류: ${error}`); return; } console.log(`stdout: ${stdout}`); console.error(`stderr: ${stderr}`); });
3. execFile()
- 용도: 파일 실행을 위한 전용 메서드.
- 특징:
- 쉘을 거치지 않고 직접 실행.
- 보안상 유리하며, 인자 전달이 간편.
- 실행 파일과 인자를 배열로 전달.
- 사용 예:
const { execFile } = require('child_process'); execFile('node', ['-v'], (error, stdout, stderr) => { if (error) { console.error(`오류: ${error}`); return; } console.log(`stdout: ${stdout}`); console.error(`stderr: ${stderr}`); });
4. fork()
- 용도: Node.js의 자식 프로세스를 생성하는 데 특화.
- 특징:
- 새로운 V8 인스턴스를 생성하고, 부모 프로세스와 IPC(Inter-Process Communication)를 지원.
- 주로 Node.js 애플리케이션에서 사용.
- 사용 예:
const { fork } = require('child_process'); const child = fork('child.js'); child.on('message', (message) => { console.log(`자식 프로세스에서 메시지: ${message}`); }); child.send('안녕하세요, 자식 프로세스!');