node_readline (逐行读取)

node官方文档

用于逐行读取文件流, 和终端交互

读取文件流

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

var rl = readline.createInterface({
  input: fs.createReadStream('a.js'),
  crlfDelay: Infinity
});

rl.on('line', lineFd =>{
  console.log( lineFd);
});

// print
第一行
第2行
第3行
第4行

终端交互

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

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

function random(min, max) {
  return Math.random() * (max - min + 1)
}

function logger(target, obj = {}) {
  var inspect = util.inspect;
  if (typeof obj === 'object') {
    Object.assign(inspect.styles, obj);
  } else {
    Object.assign(inspect.styles, {
      [typeof target]: obj
    });
  }
  return inspect(target, {colors: true}).replace(/'/g, '');
}

class flEvent {
  constructor() {}

  // 流被暂停
  pause() {
    rl.on('pause', () => {});
  }

  // 流被恢复
  resume() {
    rl.on('resume', () => {
      this.downloadTimer = setInterval(() => this.downloadFeedback(), this.t);
    });
  }
}

// 模拟下载文件
class Test extends flEvent {
  constructor() {
    super();
    this.progress = 1;
    this.downloadTimer;
    this.t = 1000 * 1;
  }
  run() {
    this.sigint();
    this.pause();
    this.resume();

    this.hello();
  }

  // 是否确定下载
  hello() {
    rl.question( logger('你确定下载这个文件吗? yes/no  >', 'green'), data => {
      if (this.isDownload(data)) {
        rl.close();
      } else {
        this.downloading()
      }
    })
  }

  // 下载中
  downloading() {
    rl.write(`开始下载! ${logger(this.progress, 'yellow')}% \n`);
    // 每隔1秒 更与用户反馈
    this.downloadTimer = setInterval(() => this.downloadFeedback(), this.t);
  }

  // 监听ctrl+c的退出事件
  sigint() {
    rl.on('SIGINT', () => {
      clearInterval(this.downloadTimer);
      util.inspect.styles.string = 'red'
      rl.question( logger("确定要退出下载吗?yes/no >", 'red'), data => {
        rl.pause();
        if (!this.isDownload(data)) {
          rl.close(); // yes关闭流
          return;
        } else {
          rl.resume(); // no重启流
        }
      });
    });
  }
  downloadFeedback() {
    var num = Math.floor(random(10, 20));
    this.progress += num;
    if (this.isDownloadOk(this.progress)) {
      rl.write(`正在下载! ${logger('100', 'green')}% \n`);
      rl.write( logger('全部下载完成!! ^_^', 'green') );
      rl.close();
      clearInterval(this.downloadTimer);
      this.downloadTimer = num = null;
      return;
    }
    rl.write(`正在下载! ${logger(this.progress, 'yellow')}% \n`);
  }

  isDownload(data) {
    if (data.match(/^y(es)?$/i)) {
      return false;
    } else {
      return true;
    }
  }

  isDownloadOk(num) {
    if (num >= 100) {
      return true;
    } else {
      return false;
    }
  }
}

var test = new Test();
test.run();
posted @ 2018-01-04 21:45  Ajanuw  阅读(489)  评论(0编辑  收藏  举报