Node.js 文件输入

最近在尝试用 JavaScript (Node.js) 写题。为此,特地看了 ECMAScript 2017 Language Specification(大雾)。写题一般是从文件输入,确切地说是,将 stdin 重定向到文件。在C/C++ 中这可以通过 freopen 函数很方便地实现, 因而想知道 Node.js 是否提供类似的函数。查看 Node.js v6.11.1 API 文档 中关于 Readline 模块(module)的介绍,恰好发现了一个例子:
Example: Read File Stream Line-by-Line

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

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

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

需要指出,Node.js 的输入输出是通过 Stream 模块实现的,类似于 C++ 中的流。

据此,我实现了将 stdin 重定向到文件:

const readline = require('readline');
const fs = require('fs');
var lines = [], cur = 0;


function cb(err){
    const rl = readline.createInterface({input: (err? process.stdin: fs.createReadStream("in.txt"))}).on('line', (line) => {
        lines[cur++] = line;
    }).on('close', () => {
        cur = 0;
        main();
    });
}

// With the asynchronous methods, there is no guaranteed ordering.

fs.access("in.txt", cb);

function readLine(){
    return lines[cur++];
}

function main(){
// ...
}

此法有个问题:无法处理强制在线的情况。
这种方式先把所有输入读进来,存起来;再进行处理。与能否处理强制在线无关。

posted @ 2017-07-31 17:32  Pat  阅读(484)  评论(0编辑  收藏  举报