将 stdin 中的所有文本读取为字符串 [英] Read all text from stdin to a string

查看:51
本文介绍了将 stdin 中的所有文本读取为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Node.js 编写一个程序,它(在某些情况下)希望充当一个简单的过滤器:从标准输入读取所有内容(直到文件末尾),进行一些处理,将结果写入标准输出.

I'm writing a program in Node.js that (in some situations) wants to act as a simple filter: read everything from stdin (up to end of file), do some processing, write the result to stdout.

您如何执行从标准输入读取所有内容"部分?到目前为止,我找到的最接近的解决方案似乎可以从控制台一次一行运行,或者仅在 stdin 是文件而不是管道时才起作用.

How do you do the 'read everything from stdin' part? The closest solutions I've found so far, seem to work either for one line at a time from the console, or else only work when stdin is a file not a pipe.

推荐答案

我的样板文件很像上面评论中描述的解决方案——在顶层提供它,因为它是最简单的方法要做到这一点,它不应该只在评论中.

My boiler-plate for this one is a lot like the solution described in a comment above -- offering it at the top level because it's very much the simplest way to do this and it shouldn't be only in a comment.

var fs = require('fs');
var data = fs.readFileSync(0, 'utf-8');
// Data now points to a buffer containing the file's contents

这篇关于将 stdin 中的所有文本读取为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆