nodejs的nodejs readline详解怎么支持字符串逐行读取

查看: 883|回复: 9
parseInt(“1”)
#include #include int main() { fstream fin(&data.txt&); //打开文件 string ReadL while(getline(fin,ReadLine)) //逐行读取,直到结束 { ... } fin.close(); return 0 }
dongzhihang
import java.io.BufferedInputS import java.io.F import java.io.FileInputS import java.io.IOE public class ReadFileTest { public static void main(String[] args) throws IOException { String temp=&&; Buffer...
你这东西是linux环境下的东西吧。。用shell脚本,扩展了正则表达式的egrep就行了 egrep 'RX|TX' input.txt & output.txt 如果是C语言的话,用readline逐行逐行读取,找到开头,读入RX当行,再读入下一行。之后同样的继续readline扫描后面字符串就...
//用BufferedReader类,我想你应该看的懂 String dz=&D:\\myedipsework\\ajax\\WebRoot\\update.txt&; InputStream in=new FileInputStream(dz);// BufferedReader in2=new BufferedReader(new InputStreamReader(in)); String y=&&; while((y=in...
nodejs 可以 直接 require JSON文件的....跟require JS文件一样 我想把数据库相关的地址端口,账号密码等等写到一个json文件里,然后node从json里读取 我用的mongoskin,我现在是在代码里写死的,比如: var db = require('mongoskin').db('root...
ubuntu 14。04 nodejs装上了输入node没反应输入nodejs才进入的交互模式 随后安装npm成功了 但是随后安装 n失败了 安装supervisor成功了 但是输入 supervisor来启动...
这样弄数组不越界才怪:v的大小为n+1,在for循环里i是可以到2*n的,看来是初学java。 把for循环改一下: for (int i = 0; i & i++) { v[i] = Integer.parseInt(b[i]); }
python中readline()是用来读取文本文件中的一行。 readline和readlines,read都是用来读取文件内容,readline()每次读取一行,当前位置移到下一行;readlines()读取整个文件所有行,保存在一个列表(list)变量中,每行作为一个元素;read(size)从...
public static String readString(String pathname) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(pathname)); StringBuilder sb = new StringBuilder();; String line = &&; while ((line = reader.readLi...
城市论坛手机客户端上线关于 Readline 类,获取用户输入方法时遇到一个诡异的问题 - CNode技术社区
这家伙很懒,什么个性签名都没有留下。
var readline = require(‘readline’);
var rl = readline.createInterface({
input:process.stdin,
output:process.stdout
rl.question(“what do you think of node.js?\n”,function(answer){
console.log(answer);
rl.close();
这个是几乎是照搬的nodejs上的例子,但是发现一个问题:
首先cmd会打印what do you think of node.js?这句话等我输入。
当我输入比如一个aaaa,然后我想删掉两个,是用退格键的时候,what do you think of node.js?这局话会再次打印,点一次退格键就会打印一次,请问这是为什么?谢谢
PS:顺便问一下,问题里想上传图片只能是用网络图片吗?我本地的截图怎么贴上来?
CNode 社区为国内最专业的 Node.js 开源技术社区,致力于 Node.js 的技术研究。
服务器赞助商为
,存储赞助商为
,由提供应用性能服务。
新手搭建 Node.js 服务器,推荐使用无需备案的REPL && Read-Eval-Print-Loop.
00.一门好的编程语言的必要条件
REPL并不是什么高大上的东西,简单的说就是一个从命令行程序,读取终端输入,处理,打印结果,如此循环。这是一门比较全面的编程语言的基础。
刚开始接触NodeJS,以为就是一个服务端Js,但学习了一段时间之后才感受到它的强大和魅力。如果说Java是编程游戏里一个喜欢循规蹈矩的古板选手,JavaScript就是一个天马行空的飘逸选手。刚开始转型异步编程非常不习惯,慢慢的懂得,异步编程,是一种思维。
01.依葫芦画不出瓢
一个命令行读取输入,处理的程序,Java可以写一个while循环来不停的用Scanner来readLine,但是如果模仿Java用JS就有点麻烦了,
var rl = require('readline');
while(true) {
rl.on('line',function(data){
//to deal data
这样很显然是不行滴,不过习惯了同步编程的猿们说不定会这样干,JavaScript的异步意味着非阻塞式的设计,不会因为等用户输入阻塞下一次循环。所以要告诉JavaScript在这一次处理完之后,再进行下一次读取(回调),那么问题来了,臭名昭著的Callback hell就有可能发生了。
10.如何正确画瓢,还要看起来舒服
解决方案1:使用async,co,q, promise等等机制来同步
解决方案2:对于一个REPL程序,逻辑很简单,如果实现一个链式调用的接口就好了,像这样:
read("var1", function(data){}).read("var2",function(data){})...
写原生代码比使用开源库更加容易调试,而且杀鸡焉用牛刀,不麻烦co这样的模块了,q 这种then()的链式调用差强人意,想做什么就直接 .xx().xx()更直观。
用起来简单的东西,背后一定是用更复杂或更精巧的方式掩盖了其真实的复杂度。
var readline = require('readline');
//非常好用的Node自带库
//Singleton
var questions = [];
//处理队列
var cursor = 0;
function dealQuestions(_self) {
//递归处理队列中的读取请求
if(cursor &= questions.length) {
cursor = 0;questions = [];
rl.close();
rl.question(questions[cursor].question, function (data) {
questions[cursor].deal(data);
dealQuestions();
//读取处理完毕回调
var easyREPL = function(){
if(rl == null) {
//初始化模块
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
* @description : a liner api to get console input
* @param : question to ask , function to deal answer
easyREPL.prototype.question = function(question,dealAnswer){
easyREPL();
rl.prompt();
var _self =
//保存this指针
questions.push({question:question,deal:dealAnswer});
//加入处理队列
if(questions.length == 1) {
dealQuestions(_self);
//实现链式调用的关键:返回this
exports.REPL_Mode = easyREPL;
测试代码:test.js
var easyREPL = require("./repl").REPL_M
var test = new easyREPL();
/* comment following codes to test command mode */
test.question("Input name:" , function(data) {
console.log("Get name:"+data);
}).question("Input password:",function(data){
console.log("Get password:"+data);
}).question("Input Email:",function(data){
console.log("Get email:"+data);
这是一个引子,NodeJS能做的事情太多了,另外还做了一个解析输入命令的程序,代码比这个多,但是不够精髓,还是不放了。
阅读(...) 评论()open()成功执行后返回一个文件对象,以后所有对该文件的操作都可以通过这个“句柄”来进行,现在主要讨论下常用的输入以及输出操作。
read()方法用于直接读取字节到字符串中,可以接参数给定最多读取的字节数,如果没有给定,则文件读取到末尾。
readline()方法读取打开文件的一行(读取下个行结束符之前的所有字节),然后整行,包括行结束符,作为字符串返回。
readlines()方法读取所有行然后把它们作为一个字符串列表返回
文件/root/2.txt的内容如下,分别使用上面的三个方法来读取,注意区别:
cat /root/2.txt
I'll write this message for you
hehe,that's will be ok.
&&&&fobj = open('/root/2.txt')
##默认已只读方式打开
&&&&a = fobj.read()
"I'll write this message for you\nhehe,that's will be ok.\n"
##直接读取字节到字符串中,包括了换行符
&&&& print a
I'll write this message for you
hehe,that's will be ok.
&&&&fobj.close()
##关闭打开的文件
readline():
&&&& fobj = open('/root/2.txt')
= fobj.readline()
"I'll write this message for you\n"
##整行,包括行结束符,作为字符串返回
&&&&c = fobj.readline()
&&&&"hehe,that's will be ok.\n"
##整行,包括行结束符,作为字符串返回
&&&&fobj.close()
readlines():
&&&&fobj = open('/root/2.txt')
&&&& d = fobj.readlines()
["I'll write this message for you\n", "hehe,that's will be ok.\n"]
##读取所有行然后把它们作为一个字符串列表返回
&&&&fobj.close()
write()方法和read()、readline()方法相反,将字符串写入到文件中。
和readlines()方法一样,writelines()方法是针对列表的操作。它接收一个字符串列表作为参数,将他们写入到文件中,换行符不会自动的加入,因此,需要显式的加入换行符。
&&& &fobj = open('/root/3.txt','w')
###确保/root/3.txt没有存在,如果存在,则会首先清空,然后写入。
&&& &msg = ['write date','to 3.txt','finish']
###这里没有显式的给出换行符
&&& &for m in msg:
fobj.write(m)
&&& &fobj.close()
cat /root/3.txt
write dateto 3.txtfinish
&&&&fobj = open('/root/3.txt','w')
###覆盖之前的数据
&&&&msg = ['write date\n','to 3.txt\n','finish\n']
###显式给出换行符
&&& &for m in msg:
fobj.write(m)
&&& &fobj.close()
cat /root/3.txt
write date
writelines():
&&&&fobj = open('/root/3.txt','w')
&&&&msg = ['write date\n','to 3.txt\n','finish\n']
&&&&fobj.writelines(msg)
&&&&fobj.close()
cat /root/3.txt
write date
<span class="tipso_style" id="tip-p" data-tipso='
您可以选择一种方式打赏本站
支付宝扫一扫打赏
微信钱包扫描打赏
你可能喜欢
12345678910
12345678910
关于本站 本站以分享运维技术为主,欢迎大家参与技术分享,同时也欢迎大家吐槽,本站提供以下交流圈:QQ群①:*****(满)QQ群②:6690706 QQ群③: QQ群④:(新) 微信公众号:ttlsacom 商务合作QQ:node.js - Read Nth line of file in NodeJS - Stack Overflow
to customize your list.
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
J it only takes a minute:
Join the Stack Overflow community to:
Ask programming questions
Answer and help your peers
Get recognized for your expertise
I'm attempting to extract a single line of a file, given that I know the pathname and the line number, ideally I'd like to do this without reading any more of the file than is necessary.
For the purpose I'm using here, it doesn't matter if this is async or sync.
My current (bad) implementation looks like this:
function get_line(filename, line_no, callback) {
line_no = parseInt(line_no);
var data = fs.readFileSync(filename, 'utf8');
var lines = data.split("\n");
for (var l in lines) {
if (l == line_no - 1) {
callback(null, lines[l].trim());
throw new Error('File end reached without finding line');
I tried to do something with a createReadStream, but the data events never seemed to fire. Can anyone provide a direct solution to this problem, or point me towards some NodeJS filesystem interaction documentation that is a little more example driven than the standard library API docs?
2,19931218
With readable stream
var fs = require('fs');
function get_line(filename, line_no, callback) {
var stream = fs.createReadStream(filename, {
flags: 'r',
encoding: 'utf-8',
mode: 0666,
bufferSize: 64 * 1024
var fileData = '';
stream.on('data', function(data){
fileData +=
// The next lines should be improved
var lines = fileData.split("\n");
if(lines.length &= +line_no){
stream.destroy();
callback(null, lines[+line_no]);
stream.on('error', function(){
callback('Error', null);
stream.on('end', function(){
callback('File end reached without finding line', null);
get_line('./file.txt', 1, function(err, line){
console.log('The line: ' + line);
Direct solution:
You should use the slice method instead of a loop.
var fs = require('fs');
function get_line(filename, line_no, callback) {
var data = fs.readFileSync(filename, 'utf8');
var lines = data.split("\n");
if(+line_no & lines.length){
throw new Error('File end reached without finding line');
callback(null, lines[+line_no]);
get_line('./file.txt', 9, function(err, line){
console.log('The line: ' + line);
for (var l in lines) isn't the most efficient way for looping over an array, you should do this instead:
for(var i = 0, iMax = lines. i & iM i++){/* lines[i] */ }
The asynchronous way:
var fs = require('fs');
function get_line(filename, line_no, callback) {
fs.readFile(filename, function (err, data) {
// Data is a buffer that we need to convert to a string
// Improvement: loop over the buffer and stop when the line is reached
var lines = data.toString('utf-8').split("\n");
if(+line_no & lines.length){
return callback('File end reached without finding line', null);
callback(null, lines[+line_no]);
get_line('./file.txt', 9, function(err, line){
console.log('The line: ' + line);
without reading any more of the file than is necessary
EDIT: the module is unmaintained, I recommend to use other modules to read line by line, for example, using transform streams:
var n = 10;
//Internally it uses a buffer, default 16KB, but you can reduce it to, for example, 4KB doing:
//new BufferedReader ("file", { encoding: "utf8", bufferSize: 4*1024 })
new BufferedReader ("file", { encoding: "utf8" })
.on ("error", function (error){
console.log (error);
.on ("line", function (line){
if (!--n){
//With interrupt you can stop the reading
this.interrupt ();
.on ("end", function (){
//your Nth line!
console.log (l);
8,718105793
You can improve a lot the performance of FGRibreau answer by deleting previous data in "fileData" variable.
function(file, line_no, cb){
var stream = fs.createReadStream(file, {
flags: 'r',
encoding: 'utf-8',
mode: '0666',
bufferSize: 64 * 1024
var fileData = '';
stream.on('data', function(data){
fileData +=
var lines = fileData.split('\n');
if(lines.length &= +line_no){
stream.destroy();
cb(null, lines[+line_no]);
// Add this else condition to remove all unnecesary data from the variable
fileData = Array(lines.length).join('\n');
stream.on('error', function(){
cb('Error', null);
stream.on('end', function(){
cb('File end reached without finding line', null);
Using a 70000 lines file, to display line n°50000 I got those results:
For the same example with the else I got the following:
This is also implies a much lower memory consumption.
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you&#39;re looking for?
Browse other questions tagged
The week&#39;s top questions and answers
Important community announcements
Questions that need answers
By subscribing, you agree to the
Stack Overflow works best with JavaScript enabled

我要回帖

更多关于 java逐行读取字符串 的文章

 

随机推荐