ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spawn을 활용한 배치 스크립트 (자동 실행)
    자바스크립트/모듈 & 내장함수 2023. 11. 7. 04:54

     

    spawn을 통해 새로운 프로세스를 시작 할 수 있으며,

    해당 프로세스의 입출력 조작 또한 가능하다.

     

    import { spawn } from 'child_process';
    //const { spawn } = require('child_process');
    
    const command = 'node';
    const args = ['index.js'];
    const childProcess = spawn(command, args, {
      stdio: 'pipe',
      shell: true,
    });​

    node index.js란 터미널 명령어를 실행한 프로세스 생성

     

    const input1 = '14000\n';  // 수정된 입력값
    const input2 = '1,2,3,4,5,6\n';  // 수정된 입력값
    const input3 = '7\n';  // 수정된 입력값
    
    childProcess.stdin.write(input1);
    setTimeout(() => {
        childProcess.stdin.write(input2);
        setTimeout(() => {
          childProcess.stdin.write(input3);
          childProcess.stdin.end();
        }, 500);
      }, 500);

     

    readLine과 같은 함수로 사용자 입력을 받는다면

    stdin.write로 input값을 넣어준다.

    입력이 여러번이라면 setTimeout()으로 시간 간격을 준다.

     

     

    childProcess.stdout.on('data', (data) => {
      console.log(data.toString());
    });
    
    childProcess.stderr.on('data', (data) => {
        console.error(data.toString()); // 출력된 에러 메시지를 콘솔에 표시
      });
    
    childProcess.on('error', (err) => {
      console.error('오류 발생:', err);
    });
    
    childProcess.on('close', (code) => {
      console.log('프로세스 종료. 종료 코드:',code);
    });

    프로세스의 출력이나 에러, 종료를 감지한다.

    또한 콘솔에 출력되는 에러메세지는 stderr로 감지한다.

     

     

     

     

     

    전체 코드

    import { spawn } from 'child_process';
    
    const command = 'node';
    const args = ['index.js'];
    const input1 = '14000\n';  // 수정된 입력값
    const input2 = '1,2,3,4,5,6\n';  // 수정된 입력값
    const input3 = '7\n';  // 수정된 입력값
    const childProcess = spawn(command, args, {
      stdio: 'pipe',
      shell: true,
    });
    
    childProcess.stdin.write(input1);
    setTimeout(() => {
        childProcess.stdin.write(input2);
        setTimeout(() => {
          childProcess.stdin.write(input3);
          childProcess.stdin.end();
        }, 500);
      }, 500);
    
    childProcess.stdout.on('data', (data) => {
      console.log(data.toString());
    });
    
    childProcess.stderr.on('data', (data) => {
        console.error(data.toString()); // 출력된 에러 메시지를 콘솔에 표시
      });
    
    childProcess.on('error', (err) => {
      console.error('오류 발생:', err);
    });
    
    childProcess.on('close', (code) => {
      console.log('프로세스 종료. 종료 코드:',code);
    });

    '자바스크립트 > 모듈 & 내장함수' 카테고리의 다른 글

    JS Math  (0) 2023.08.12
    NET 모듈로 서버 & 클라이언트 만들기  (0) 2023.08.08
    crypto 모듈 - 암복호화, MAC, 난수, 서명  (0) 2023.08.06
    crypto 모듈 - 해싱  (0) 2023.08.06
    setTimeout(), setInterval()  (0) 2023.08.05
Designed by Tistory.