简体   繁体   中英

NodeJS - Reading Line By Line Function + While Loop

I am currently have an issue where I am trying to read a file line by line and then output the contents of said file onto the webpage hosted by nodejs. I am trying to use a while loop, but Im not sure its working, and I don't really know what otherway to go about it. I could use some help.

 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"); 

Thanks, Sage

Following options let you Either read whole file accumulate results and send as a one response to web-page Or if you have web-socket open or other form of connection with client you can send earch line that is read and processed if needed.

Option 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);
});

Option 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 
 });

For complete working solution get this Github Repo and run line_by_line.js

Happy Helping!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM