Node.js

nodejs console 입력받기 (readline, readline-sync module)

blackbearwow 2022. 7. 20. 13:31

https://nodejs.dev/learn/accept-input-from-the-command-line-in-nodejs

https://nodejs.org/api/readline.html

- 영문 공식문서

https://hyex.github.io/javascript/2020/08/24/javascript-nodejs-input/

- 참고한 블로그

 

1. readline 모듈을 사용하면 nodejs에서도 콘솔 입력이 가능하다.

 

- 한번 입력받기

const rl = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on("line", function(line) { 
    console.log("input:", line);
    rl.close()
})
rl.on("close", function() {	process.exit() })

- 계속 입력받기

rl.close()를 지워주면 계속 입력받을 수 있다.

const rl = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.on("line", function(line) { 
    console.log("input:", line);
})
rl.on("close", function() {	process.exit() })

 

2. readline-sync모듈을 사용하면 더욱 편리하게 입력 가능하다! 이걸 왜 이제야 알았는지 ㅠㅠ

설치:

npm install readline-sync

 

설치 후 다음 코드를 실행하면 c언어의 scanf(), python의 input()등의 동기 입력이 가능하다

const reader = require('readline-sync');
while(true) {
    let input = reader.question('Read from console: ');
    console.log(input);
}

 

와! 드디어 js에서도 동기 입력이 가능하다는걸 알았다!

'Node.js' 카테고리의 다른 글

package.json  (0) 2022.07.21
axios : XMLHttpRequests 모듈  (0) 2022.07.20
nodejs 외부 js파일(모듈) 함수 호출하기  (0) 2022.07.20
hello world!  (0) 2022.07.15
Node.js 설치  (0) 2022.07.15