joonsei
Hello, world!
joonsei
전체 방문자
오늘
어제
  • 분류 전체보기 (32)
    • nodejs (7)
    • javascript (3)
    • Elasticsearch (11)
    • Electron (1)
    • oracle (1)
    • etc (7)
    • MongoDB (1)

인기 글

최근 댓글

최근 글

joonsei
nodejs

child_process에서 spawn, exec 차이

2017. 7. 20. 12:47
  • spawn : stream 리턴, 비동기
  • exec : buffer 리턴, 동기

자식 프로세스로부터 큰 바이너리 데이터를 리턴받는 경우라면 spawn을, 간단한 상태 메시지만 받는 것이라면 exec를 쓴다.

// Dependencies
var fs = require('fs');
var url = require('url');
var http = require('http');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

// App variables
var file_url = 'http://upload.wikimedia.org/wikipedia/commons/4/4f/Big%26Small_edit_1.jpg';
var DOWNLOAD_DIR = './downloads/';

// We will be downloading the files to a directory, so make sure it's there
// This step is not required if you have manually created the directory
var mkdir = 'mkdir -p ' + DOWNLOAD_DIR;
var child = exec(mkdir, function(err, stdout, stderr) {
  if (err) throw err;
  else download_file_httpget(file_url);
});

// Function for downloading file using HTTP.get
var download_file_httpget = function(file_url) {
  var options = {
    host: url.parse(file_url).host,
    port: 80,
    path: url.parse(file_url).pathname
  };

  var file_name = url.parse(file_url).pathname.split('/').pop();
  var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);

  http.get(options, function(res) {
    res.on('data', function(data) {
      file.write(data);
    }).on('end', function() {
      file.end();
      console.log(file_name + ' downloaded to ' + DOWNLOAD_DIR);
    });
  });
};
저작자표시 (새창열림)
    'nodejs' 카테고리의 다른 글
    • body-parser (urlencoded, extended 옵션)
    • req.body null 일때
    • nodejs 기본 메모리 제한
    • node.js를 이용하여 IOS 푸시 보내기
    joonsei
    joonsei
    IT 개발자의 소소한 기술 이야기.

    티스토리툴바