NodeJS - 逐行读取函数+循环

时间:2016-03-06 05:44:50

标签: javascript linux node.js

我目前遇到的问题是我尝试逐行读取文件,然后将所述文件的内容输出到nodejs托管的网页上。我试图使用while循环,但我不确定它的工作,我真的不知道其他什么去做。我可以使用一些帮助。

var sys = require('util');
var exec = require('child_process').exec; 
//Find Audio Files in Audio Directory
exec("~/music_Controller/./music_Find.sh");

var contents = '';

var fs = require('fs');

//Reads file defined on input (readLines(input, func);) and reads them line by line
function readLines(input, func) {
  var remaining = '';

  input.on('data', function(data) {
    remaining += data;
    var index = remaining.indexOf('\n');
    while (index > -1) {
      var line = remaining.substring(0, index);
      remaining = remaining.substring(index + 1);
      func(line);
      index = remaining.indexOf('\n');
    }
  });

  input.on('end', function() {
    if (remaining.length > 0) {
      func(remaining);
    }
  });
}

function func(data) {
  contents = data;
}




readLines(input, func);



function puts(error, stdout, stderr) { sys.puts(stdout) }

var http = require('http');
var server = http.createServer(function(request, response) {
	var input = fs.createReadStream('/root/music_Controller/songs.txt');
  while(readLines(input, func)){
  	response.write(contents);

  }

  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("<!DOCTYPE html>");
  response.write("<html>");
  response.write("<head>");
  response.write("<title>Hello World Page</title>");
  response.write("</head>");
  response.write("<body>");
  response.write("Hello World!");
  response.write("</body>");
  response.write("</html>");
  response.end();

  //Execute Shell Script/Command
  exec("play ~/music_Controller/song.mp3", puts);
  console.log("exec");
});

server.listen(8911);
console.log("Server is listening");

谢谢, 鼠尾草

1 个答案:

答案 0 :(得分:3)

以下选项允许您读取整个文件累积结果并作为一个响应发送到网页页面或者如果您打开了网络套接字或与客户端的其他形式的连接,您可以发送在需要时读取和处理的earch行

选项1:

Tail = require('tail').Tail;

tail = new Tail("/root/music_Controller/songs.txt", "\n", {}, true);

tail.on("line", function(data) {
  console.log(data);
});

tail.on("error", function(error) {
  console.log('ERROR: ', error);
});

选项2:npm install linebyline

var readline = require('linebyline'),
rl = readline('./somefile.txt');
rl.on('line', function(line, lineCount, byteCount) {
     // do something with the line of text 
})
.on('error', function(e) {
    // something went wrong 
 });

要获得完整的工作解决方案,请获取此Github Repo并运行line_by_line.js

快乐帮助!