[컴] nodejs 의 readline 사용법

node js / node 의 / 파일을 1줄씩 한줄씩 읽는 법 / 노드

nodejs 의 readline 사용법

readline 을 callback 을 이용해서 사용

const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
  input: fs.createReadStream('sample.txt'),
  crlfDelay: Infinity
});

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

readline 을 async/await 을 이용해서 사용

const fs = require('fs');
const readline = require('readline');

async function processLineByLine() {
  const fileStream = fs.createReadStream('input.txt');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  // Note: we use the crlfDelay option to recognize all instances of CR LF
  // ('\r\n') in input.txt as a single line break.

  for await (const line of rl) {
    // Each line in input.txt will be successively available here as `line`.
    console.log(`Line from file: ${line}`);
  }
}

processLineByLine();

for await...of loop 이 약간 느릴 수 있다고 한다. 그래서 아래처럼 하면 좀 낫다고 한다.

const { once } = require('events');
const { createReadStream } = require('fs');
const { createInterface } = require('readline');

(async function processLineByLine() {
  try {
    const rl = createInterface({
      input: createReadStream('big-file.txt'),
      crlfDelay: Infinity
    });

    rl.on('line', (line) => {
      // Process the line.
    });

    await once(rl, 'close');

    console.log('File processed.');
  } catch (err) {
    console.error(err);
  }
})();

read 후 write 하려면


// read 후 write 하려면

let rf = readline.createInterface({
  input: fs.createReadStream(file.path),
  terminal: false
});
rf.on('error', (err) => { console.log(err); });

let wf = fs.createWriteStream(file.destination + file.originalname);

rf.on('line', (line) => {
  if (line.match(/mykey/)) {
    line = line.replace(/mykey/, 'mykey2');
  }
  wf.write(line + '\n');
});
rf.on('close', () => {
  wf.close();
});

See Also

  1. 쿠…sal: [컴] read file in nodejs

댓글 없음:

댓글 쓰기