원문 링크 - http://www.catonmat.net/blog/nodejs-modules-read/

오늘은 node.js modules you should know about 연재의 여섯번째 시간이다.

지난 시간까지는 아래와 같은 node 모듈들을 다뤘었다.

1회 연재 - dnode (RPC 라이브러리)

2회 연재 - optimist (옵션 파서)

3회 연재 - lazy (lazy 리스트 처리)

4회 연재 - request (HTTP 스트림 처리)

5회 연재 - hashish (해시 처리)

오늘은 굉장히 새로운 read라는 모듈을 소개하려고 한다. read는 npm을 개발한 Isaacs Z. Schlueter에 의해 얼마 전에 작성됐다. read 모듈은 기본적으로 node를 위한 read(1)다. 여러분은 이것을 이용해 표준입력(stdin)으로부터 쉽게 입력값을 읽어들일 수 있다.

다음은 예제다.

var read = require('read');

read({ prompt : 'Username: ' }, function (err, user) {
  read({ prompt : 'Password: ', silent : true }, function (err, pass) {
    console.log(user, pass);
    process.stdin.destroy();
  });
})

위 코드와 같이 중첩 함수를 사용하면 코드가 지저분해 보이기 때문에, James Halliday가 개발한 비동기 흐름을 제어하는 seq 라는 라이브러리를 사용해보자. (조만간 연재에서 이 모듈을 다룰 것이다.) 다음은 seq를 사용한 후에 바뀐 코드다.

var read = require('read');
var Seq = require('seq');

Seq()
  .seq(function () {
    read({ prompt : 'Username: ' }, this.into('user'));
  })
  .seq(function () {
    read({ prompt : 'Password: ', silent : true }, this.into('pass'));
  })
  .seq(function (pass) {
    console.log(this.vars.user, this.vars.pass);
  });

다음은 read가 지원하는 옵션들이다.

prompt  - 입력을 받기 전에 출력창에 나타날 값 지정.
silent  - 유저가 입력한 내용을 출력하지 마라.
num     - 터미널에서 읽어 올 최대 문자수.
delim   - 입력 완료를 나타내는 문자. 디폴트: "\n"
timeout - 유저 입력을 기다리는 최대 시간(단위: ms).

주의: silent가 true이거나 num이 설정됐거나, delim이 "\n"가 아닌 다른 값으로 되어 있다면, read는 raw모드로 동작해서, 문자 단위로 읽을 것이다.

항상 그랬던 것처럼 npm을 통해 read를 설치할 수 있다.

npm install read

Enjoy!

If you love these articles, subscribe to my blog for more, follow me on Twitter to find about my adventures, and watch me produce code on GitHub!