관리 메뉴

Silver Library (Archived)

Note of readline module - Node.js 본문

CS Library/JavaScript - Data Structure

Note of readline module - Node.js

Chesed Kim 2021. 7. 24. 14:35
반응형

좀 더 작정하고 알아보는 readline module. 그 1편.

 

확실한 사실:

이건 node.js 의 Readline 과 연관이 있습니다.

 

The readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time. It can be accessed using:

const readline = require('readline');

The following simple example illustrates the basic use of the readline module.

const readline = require('readline');

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

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log(`Thank you for your valuable feedback: ${answer}`);

  rl.close();
});

Once this code is invoked, the Node.js application will not terminate until the readline.Interface is closed because the interface waits for data to be received on the input stream.


// readline module 을 import 하기

const readline = require("readline");

 

// interface object (인터페이스 객체) 생성

// process 의 입출력(input/output) stream 을 input 과 output 에 할당

const rl = readline.createInterface({

// readline module 을 import 하기

const readline = require("readline");



// interface object (인터페이스 객체) 생성

// process 의 입출력(input/output) stream 을 input 과 output 에 할당

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

rl.on("line", function (line) {
	const input = line.split(" ");
    
    const result = Number(input[0]) * Number (input[1]);
    console.log(result);
    
// readline 을 close method 로 닫기.
	rl.close();
}).on("close", function () {
	process.exit();
});

잠깐! 왜 rl.close(); ?
- The rl.close() method closes the readline.Interface instance and relinquishes control over the input and output streams. When called, the 'close' event will be emitted.
- Calling rl.close() does not immediately stop other events (including 'line') from being emitted by the readline.Interface instance.

 

그럼 저 .on() method 는 정체가 뭘까?

Because of it's asynchronous nature Node.js can be a bit tricky with this kind of things. It means that when your code is executing, it is firing the rl.on('line') handler and passing to the next call which in our case is the console.log. The problem in your actual code is not that the array is not filling up, it's that you are expecting it to be populated to early. Here is an example of how you could fix your problem:

var rl = require('readline').createInterface({
  input: require('fs').createReadStream('small.csv')
});

global.myarray = [];
rl.on('line', function (line) {
  console.log('Line from file:', line);
  global.myarray.push(line);
});

rl.on('close', function () {
    console.log(global.myarray);
});

In this piece of code, when there is no more line to read from, the console.log will be called and there will be some data displayed.


createInterface는? 

The readline.createInterface() method creates a new readline.Interface instance.

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

Once the readline.Interface instance is created, the most common case is to listen for the 'line' event:

rl.on('line', (line) => {
  console.log(`Received: ${line}`);
});

 

If terminal is true for this instance then the output stream will get the best compatibility if it defines an output.columns property and emits a 'resize' event on the output if or when the columns ever change (process.stdout does this automatically when it is a TTY).

 

When creating a readline.Interface using stdin as input, the program will not terminate until it receives EOF (Ctrl+D on Linux/macOS, Ctrl+Z followed by Return on Windows). If you want your application to exit without waiting for user input, you can unref() the standard input stream:

process.stdin.unref();

그..그럼 process.stdout 은?

The process.stdout property returns a stream connected to stdout (fd 1). It is a net.Socket (which is a Duplex stream) unless fd 1 refers to a file, in which case it is a Writable stream.

 

For example, to copy process.stdin to process.stdout:

import { stdin, stdout } from 'process';

stdin.pipe(stdout);

process.stdout differs from other Node.js streams in important ways. See note on process I/O for more information.

 

line 은?

이에 대한 특징으로는, line 과 close 이다.

var rl = require('readline').createInterface({
  input: require('fs').createReadStream('small.csv')
});

global.myarray = [];
rl.on('line', function (line) {
  console.log('Line from file:', line);
  global.myarray.push(line);
});

rl.on('close', function () {
    console.log(global.myarray);
});

global.myarray = [];

rl.on("line", function (line) {

   console.log("Line from file:", line);

   global.myarray.push(line);

});

 

rl.on("close", function () {

   console.log(global.myarray);

});

 

The current input data being processed by node.

This can be used when collecting input from a TTY stream to retrieve the current value that has been processed thus far, prior to the line event being emitted. Once the line event has been emitted, this property will be an empty string.

Be aware that modifying the value during the instance runtime may have unintended consequences if rl.cursor is not also controlled.

If not using a TTY stream for input, use the 'line' event.

One possible use case would be as follows:

const values = ['lorem ipsum', 'dolor sit amet'];
const rl = readline.createInterface(process.stdin);
const showResults = debounce(() => {
  console.log(
    '\n',
    values.filter((val) => val.startsWith(rl.line)).join(' ')
  );
}, 300);
process.stdin.on('keypress', (c, k) => {
  showResults();
});

rl.close()

The rl.close() method closes the readline.Interface instance and relinquishes control over the input and output streams. When called, the 'close' event will be emitted.

Calling rl.close() does not immediately stop other events (including 'line') from being emitted by the readline.Interface instance.

 

그 외 도움될 링크:

https://bluehorn07.tistory.com/49

'CS Library > JavaScript - Data Structure' 카테고리의 다른 글

백준 1065 한수 - JS  (0) 2021.08.08
BJ 2562 - JS  (0) 2021.08.06
JS, for 문 - 10950 번, A+B - 3, .on method  (0) 2021.07.20
JS, for 문 - 백준 2739: 구구단  (0) 2021.07.20
JS, 백준 2884 번: 알람 시계  (0) 2021.07.20