javascript - js 代码如何使用终端获取输入文件?

标签 javascript shell

所以我需要在终端中使用输入文件,当我编写以下 cat input.txt |节点 prog.js >result.txt

我的代码是:

var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');

str.replace(/^\s*[\r\n]/gm,"").split(/\s+/).forEach(function (s) {
    return console.log(
    s === 'bob'
        ? 'boy'
        : s === 'alicia'
        ? 'girl'
        : s === 'cookie'
        ? 'dog'
        : 'unknown');
});

我需要我的代码来获取输入文档,无论用户给出的名称如何。获取用户输入的正确方法是什么?

最佳答案

如果你将一个值输出到node.js脚本,你必须监听readabledata process可用的事件监听器目的。使用data每当您使用 readable 时,事件监听器都会将流直接置于流动模式。事件监听器,您必须使用 process.stdin.read() 强制 stdin 进入流动模式。要写入另一个命令或另一个脚本,您必须使用 process.stdout.write() ,它是一个可写流。

流动模式

#!/usr/bin/env node

let chunks = "";

process.stdin.on("data", data => {
    // data is an instance of the Buffer object, we have to convert it to a string
    chunks += data.toString();
})

// the end event listener is triggered whenever there is no more data to read

process.stdin.on("end", () => {
    // pipe out the data to another command or write to a file
    process.stdout.write(chunks);
});

非流动模式

#!/usr/bin/env node

process.stdin.on("readable", () => {
    const flowingMode = process.stdin.read();
    // flowingMode will become null, whenever there is no more data to read
    if ( flowingMode )
        chunks += flowingMode.toString();
})

process.stdin.on("end", () => {
    process.stdout.write(chunks);   
})

为了防止自己承受所有这些压力,如果 readable 上有非逻辑,您可以执行以下操作:或data事件处理程序

#!/usr/bin/env node

process.stdin.pipe(process.stdout);

如果你想在 end 时做某事事件监听器被触发你应该这样做

#!/usr/bin/env node

process.stdin.pipe(process.stdout, { end: false } );

process.stdin.on("end", () => /* logic */ );

end事件监听器被触发执行您的代码

#!/usr/bin/env node

let chunk = "";

process.stdin.on("data", data => {
    chunk += data.toString();
});

process.stdin.on("end", () => {
    chunk.replace(/^\s*[\r\n]/gm,"").split(/\s+/).forEach(function (s) {
        process.stdout.write(
        s === 'bob'
        ? 'boy'
        : s === 'alicia'
           ? 'girl'
           : s === 'cookie'
               ? 'dog'
               : 'unknown');
    });
});

> cat input.txt | ./prog.js > result.txt

关于javascript - js 代码如何使用终端获取输入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52710067/

相关文章:

javascript - 在 angularJs 中从 Controller 调用同时 $http 服务?

javascript - 在 ajax 调用之前运行 javascript 函数

javascript - 用随机字母/数字替换每个选定的值

javascript - 是否可以配置 iOS 原生 HTML5 日期选择器?

node.js - 构建脚本在 Windows 上失败,但在 Linux 或 OSX 上不会

shell - "Hiding"来自 ltrace 和 strace 的系统调用

javascript - 如何让2个异步API调用相继执行

Shell脚本多行注释

c - 分析 C 程序 - Time Shell 命令

linux - 本地和 Hadoop 文件之间的差异