gpt4 book ai didi

javascript - NodeJS - 逐行读取函数 + While 循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:07:38 25 4
gpt4 key购买 nike

我目前遇到一个问题,我试图逐行读取文件,然后将所述文件的内容输出到 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:

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

帮助愉快!

关于javascript - NodeJS - 逐行读取函数 + While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35823597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com