'Technical Note'에 해당되는 글 134건

Technical Note/LINUX

test 프로세스 모두 죽이기 제1안

  # kill -9 `ps -ef | grep test | awk '{print $2}'`


test 프로세스 모두 죽이기 제2안

  # ps -ef | grep test | grep -v grep | awk '{print "kill -9",$2}' | sh -v


test 프로세스 모두 죽이기 제3안

  # killall -KILL test


test 프로세스 모두 죽이기 쉘 스크립트 

  #!/bin/sh
  for PID `ps -ef | grep test | grep -v grep | awk '{print $2}'`
  do
  kill -9 $PID
  done


test User로 실행 되어지는 모든 프로세스 죽이기

  # kill -9 `ps -ef | awk '$1=="test" {print $2}'`

저작자 표시 비영리 변경 금지


Technical Note/Node.js

ZIP a Folder in NodeJS

Here is a simple way to archive and pipe a folder in NodeJS.
First, get the fstream and tar modules:
  • npm install fstream
  • npm install tar
Do something like this on your server:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var fstream = require('fstream'),
    tar = require('tar'),
    zlib = require('zlib');
 
    res.writeHead(200, {
      'Content-Type'        'application/octet-stream',
      'Content-Disposition' 'attachment; filename=myArchive.zip',
      'Content-Encoding'    'gzip'
    });
 
    var folderWeWantToZip = '/foo/bar';
 
    /* Read the source directory */
    fstream.Reader({ 'path' : folderWeWantToZip, 'type' 'Directory' })
        .pipe(tar.Pack())/* Convert the directory to a .tar file */
        .pipe(zlib.Gzip())/* Compress the .tar file */
        .pipe(response); // Write back to the response, or wherever else...
This solution is based on an answer on StackOverflow


Technical Note/Node.js

How to download files using Node.js


There are three approaches to writing a file downloader app using Node - i. HTTP.get, ii. curl, iii. wget. I have created functions for all of them. To get the examples working makes sure you have the dependencies and app variables intact. Read the comments thoroughly, you will not only learn how to download files, but will also learn more about Node's child_process, File System, Buffers, and Streams. Let's start with HTTP.get.

Downloading using HTTP.get

HTTP.get is Node's built-in mechanism for making HTTP GET requests, which can also be used for downloading files using the HTTP protocol. The advantage of using HTTP.get is that you don't rely on any external programs to download files.

// 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 to download 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);
});
});
};

The above function is probably the best way to download files using HTTP.get in Node. Make a HTTP.get request and create a writable stream using fs.createWriteStream. Since the HTTP.get's response is a stream, it has the data event, which carries the chunks of data sent by the server. One each data event, write the data to the writeable stream. Once the server finishes sending data, close the instance of fs.createWriteStream. If you are trying to use fs.write orfs.writeFile or any of their variants, they will fail for medium to large files. Usefs.createWriteStream instead for reliable results.

Downloading using curl

To download files using curl in Node.js we will need to use Node's child_process module. We will be calling curl using child_process's spawn method. We are using spawn instead of execfor the sake of convenience - spawn returns a stream with data event and doesn't have buffer size issue unlike exec. That doesn't mean exec is inferior to spawn; in fact we will use exec to download files using wget.

// Function to download file using curl
var download_file_curl = function(file_url) {

// extract the file name
var file_name = url.parse(file_url).pathname.split('/').pop();
// create an instance of writable stream
var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);
// execute curl using child_process' spawn function
var curl = spawn('curl', [file_url]);
// add a 'data' event listener for the spawn instance
curl.stdout.on('data', function(data) { file.write(data); });
// add an 'end' event listener to close the writeable stream
curl.stdout.on('end', function(data) {
file.end();
console.log(file_name + ' downloaded to ' + DOWNLOAD_DIR);
});
// when the spawn child process exits, check if there were any errors and close the writeable stream
curl.on('exit', function(code) {
if (code != 0) {
console.log('Failed: ' + code);
}
});
};

The way data was written to the instance of fs.createWriteStream is similar to way we did for HTTP.get. The only difference is that the data and end events are listened on the stdout object ofspawn. Also we listen to spawn's exit event to make note of any errors.

Downloading using wget

Although it says downloading using wget, this example applies to downloading using curl with the -O option too. This method of downloading looks the most simple from coding point of view.

// Function to download file using wget
var download_file_wget = function(file_url) {

// extract the file name
var file_name = url.parse(file_url).pathname.split('/').pop();
// compose the wget command
var wget = 'wget -P ' + DOWNLOAD_DIR + ' ' + file_url;
// excute wget using child_process' exec function

var child = exec(wget, function(err, stdout, stderr) {
if (err) throw err;
else console.log(file_name + ' downloaded to ' + DOWNLOAD_DIR);
});
};

In the above method, we used child_process's exec function to run wget. Why exec and notspawn? Because we just want wget to tell us if the work was done properly or not, we are not interested in buffers and streams. We are making wget do all the dirty work of making request, handling data, and saving the file for us. As you might have guessed, this method is the fastest among the three methods I described.

So now the question is - which method is the best? The answer - whatever suits your need. The wgetmethod is probably the best is you want to save the files to the local disk, but certainly not if you want to send those files as a response to a current client request; for something like that you would need to use a stream. All the three methods have multiple options, you choice will ultimately depend on what your needs are. Happy downloading!

Further Reading

  1. Node.js HTTP
  2. Node.js fs
  3. Node.js Child Processes
  4. Node.js Buffers
  5. Node.js Streams


Technical Note/Node.js
http://www.hacksparrow.com/difference-between-spawn-and-exec-of-node-js-child_process.html

`spawn` `exec`가 하는 작업은 동일하지만, 

`spawn`은 스트림(stream)을 리턴하고, `exec`는 버퍼(buffer)를 리턴한다.

`spawn`은 `stdout`과 `stderr` 스트림을 포함한 객체를 리턴한다.
자식 프로세스의 표준 출력을 `stdout` 객체로 받아 처리할 수 있다.
`stdout` 객체는 `data`와 `end` 등의 이벤트를 발생한다.
`spawn`은 자식 프로세스로부터 많은 양의 데이터를 받는 경우에 유용한다.
예) 이미지 프로세싱이나 바이너리 데이터를 읽어오는 등


`exec`는 자식 프로세스 버퍼의 아웃풋을 리턴한다.
버퍼의 사이즈는 기본값은 200k이다.
만약, 자식 프로세스가 버퍼 사이즈보다 더 큰 값을 리턴하면,
"Error: maxBuffer exceeded" 오류가 나면서 프로그램이 종료될 것이다.
버퍼 사이즈를 크게 늘리면 해결할 수는 있으나,
`exec`는 큰 사이즈의 버퍼 처리를 위한 것이 아니다.
이런 경우라면 `spawn`을 사용하는 게 적합하다.
`exec`는 데이터 대신 상태 정도의 작은 결과를 출력하는 프로그램을 실행하는 용도로 사용한다.

또 하나,
`spawn`은 비동기로 실행하고, 결과도 비동기로 받는다.
`exec`는 동기로 실행하고, 결과는 비동기로 받는다.

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


상황에 따라 `spawn`  `exec`를 사용한 예


Technical Note/JAVA

Java에서 XML을 다루기 위한 API들입니다. DOM, SAX, JDOM,StAX

IBM의 developerworks에 보면 좋은 tutorial이 있습니다.
    XML 입문(한글) : http://www.ibm.com/developerworks/kr/xml/newto/

참고자료를 보면서 간단하게 정리한 내용은..

DOM(document object model) : 
   object-based(객체기반) 으로 트리구조를 이루며 XML 내용을 모두 분석하므로 느리고 메모리 사용이 많음
SAX(simple api for xml) : 
   event-based(이벤트 기반) 으로 순차적으로 읽기만 가능하며 DOM에 비해 빠르고 메모리 사용 적음
JDOM(java document object model) 
   object-based(객체기반)으로 DOM을 Java에 친숙하게 개량하고 DOM,SAX와의 상호 연동 지원
StAX(streaming api for xml) 
   cursor-based(커서 기반)으로 DOM, SAX를 보안한 방법으로 필요할때 정보를 추출

입니다.

다음은 DOM, SAX, StAX에 대한 장단점입니다.
(원본 출처가 oracle magazine이었는데 갈무리한 blog를 까먹었네요.)
□ XML 구문 분석 기술 요약    

    ㅁ 장점
    +-------------------------------------------------------------------------------------------------
    |DOM |* 사용 편의성                                                                              
    |        |* 편리한 탐색을 위한 풍부한 API 집합                                             
    |        |* 전체 트리가 메모리로 로드되므로 XML 문서에 대한 임의 액세스 허용
    +---------------------------------------------------------------------------------------
    |SAX  |* 전체 문서가 메모리에 로드되지 않으므로 메모리 소비량 감소            
    |        |* 여러 ContentHandler를 등록할 수 있는 푸시 모델                            
    +---------------------------------------------------------------------------------------
    |StAX |* 편의성과 성능을 위한 두 개의 구문 분석 모델이 포함되어 있음     
    |        |* 애플리케이션이 구문 분석을 제어하므로 여러 입력이 더 쉽게 지원됨
    |        |* 효율적인 데이타 검색을 가능하게 하는 강력한 필터링 기능 제공   
    +---------------------------------------------------------------------------------------
    
    ㅁ 단점
    +---------------------------------------------------------------------------------------
    |DOM |* 한 번에 구문 분석해야 함                                       
    |        |* 전체 트리를 메모리로 로드하는 경우 과도한 부담 발생
    |        |* 객체 유형 바인딩의 경우 일반 DOM 노드가 적합하지 않음           
    |        |  (모든 노드에 대한 객체 작성 필요)                               
    +---------------------------------------------------------------------------------------
    |SAX  |* 내장된 문서 탐색 지원 없음                            
    |        |* XML 문서에 대한 임의 액세스 없음                 
    |        |* XML 수정에 대한 지원 없음                           
    |        |* 이름 공간 범위 지정에 대한 지원 없음             
    +---------------------------------------------------------------------------------------
    |StAX |* 내장된 문서 탐색 지원 없음                           
    |        |* XML 문서에 대한 임의 액세스 없음                
    |        |* XML 수정에 대한 지원 없음                          
    +---------------------------------------------------------------------------------------
        
    ㅁ 가장 적합한 경우
    +---------------------------------------------------------------------------------------
    |DOM |* XML 문서를 수정해야 하거나 XSLT를 위한 애플리케이션            
    |        |  (읽기 전용 XML 애플리케이션에는 사용되지 않음)               
    +---------------------------------------------------------------------------------------
    |SAX  |* XML에서 읽기만 수행하는 애플리케이션                            
    |        |  (XML 문서 조작 또는 수정에는 사용되지 않음)                    
    +---------------------------------------------------------------------------------------
    |StAX |* 스트리밍 모델과 네임 스페이스에 대한 지원이 필요한 애플리케이션
    |        |  (XML 문서 조작 또는 수정에는 사용되지 않음)                     
    +---------------------------------------------------------------------------------------



이후 소스들은 참고자료를 보면서 따라해본 소스들이며 JDK 5에서 테스트 하였으며
샘플로 사용한 xml 파일은 상당히 단순합니다.

xml 샘플파일 a.xml



DOM 사용
DOM을 사용하여 XML 을 읽어 전체 읽기, 수정, 삭제, 다시 XML 파일로 저장의 작업 샘플입니다.
"Understanding DOM : http://www.ibm.com/developerworks/edu/x-dw-xudom-i.html" 를 보면서 따라한 샘플입니다.

DOM 샘플 : DOM.java




SAX 사용
"Understanding SAX : http://www.ibm.com/developerworks/edu/x-dw-xusax-i.html" 을 보면서 따라한 샘플입니다.
소스 파일이 2개 있는데 SAX.java와 필터를 사용한 SAX_Filter.java입니다.
SAX.java는 기초적인 사용 예제로 DefaultHandler라는 여러 핸들러를 implement한 껍데기 클래스입니다.
Content나 Error등의 각기 인터페이스 클래스가 제공되므로 따로 구현해도 됩니다.

SAX 샘플 : SAX.java


SAX_XMLFilter.java는 필터 기능을 넣는 방법으로 각 event 전 후에 해당 메소드들이 실행되며
XMLFilterImpl 클래스를 상속하여 구현합니다.

SAX Filter 사용 샘플 : SAX_XMLFilter.java



JDOM
일단, JDOM 홈페이지(http://www.jdom.org/) 에서 jdom.jar 를 받아야 합니다.
"Simplify XML programming with JDOM : http://www.ibm.com/developerworks/java/library/j-jdom/" 와 jdom 다운시 들어있는 샘플을 보고 돌려봤습니다.

JDOM 사용 샘플 : JDOM.java



StAX
StAX의 경우 API와 RI(구현체)가 여러가지 있습니다. (처음에 BEA에서 만들었군요)
http://stax.codehaus.org/ 와 http://woodstox.codehaus.org/ 에서 API와 RI의 .jar 를 받을 수 있는데 
아래 샘플에선 stax.codehaus.org에서 받은 라이브러리를 사용했습니다.
다른 분들은 woodstox를 사용하시는 것 같습니다.

샘플에서 XML 파일을 읽고 쓰는데 2가지 방식(XMLStreamReader와 XMLEventWriter) 이 있습니다.
참고자료의 "StAX'ing up XML, Part1,2,3" 을 보고 만들었습니다.

StAX 사용 샘플 : StAX.java



참고자료 : (IBM developerworks의 경우 일부 글들은 가입하셔야 볼 수 있습니다.)

XML 입문(한글) : http://www.ibm.com/developerworks/kr/xml/newto/

DOM
    Understanding DOM : http://www.ibm.com/developerworks/edu/x-dw-xudom-i.html
    Java와 XML 5장 DOM : http://kwon37xi.springnote.com/pages/1231818
    Java와 XML 6장 Advanced DOM : http://kwon37xi.springnote.com/pages/1231820

SAX - 홈 : http://www.saxproject.org/
    Understanding SAX : http://www.ibm.com/developerworks/edu/x-dw-xusax-i.html
    Java와 XML 3장 SAX : http://kwon37xi.springnote.com/pages/1231802
    Java와 XML 5장 Advanced SAX : http://kwon37xi.springnote.com/pages/1231814

JDOM - 홈 : http://www.jdom.org/
    Simplify XML programming with JDOM : http://www.ibm.com/developerworks/java/library/j-jdom/
    Java와 XML 7장 JDOM : http://kwon37xi.springnote.com/pages/1231824
    Java와 XML 8장 Advanced JDOM : http://kwon37xi.springnote.com/pages/1231828

StAX
    StAX'ing up XML, Part 1: An introduction to Streaming API for XML (StAX): 
        http://www.ibm.com/developerworks/library/x-stax1.html
    StAX'ing up XML, Part 2: Pull parsing and events :
        http://www.ibm.com/developerworks/java/library/x-stax2.html
    StAX'ing up XML, Part 3: Using custom events and writing XML :
        http://www.ibm.com/developerworks/xml/library/x-stax3.html
    StAX API 및 RI : 
        http://stax.codehaus.org/
        http://woodstox.codehaus.org/


1 2 3 4 ··· 27
블로그 이미지

zzikjh