Created
March 24, 2016 01:24
-
-
Save shaosh/90681be8245c2d2c26db to your computer and use it in GitHub Desktop.
Read multiple lines from a textfile and put each into an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
function readLines(input, func){ | |
var remaining = ''; | |
var array = []; | |
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, array); | |
index = remaining.indexOf('\n'); | |
} | |
}); | |
input.on('end', function(){ | |
if(remaining.length > 0){ | |
func(line, array); | |
} | |
printData(array); | |
}); | |
} | |
function func(data, array){ | |
array.push(data); | |
} | |
function printData(data){ | |
for(var i = 0; i < data.length; i++){ | |
data[i].replace('\r', ''); | |
data[i].replace('\n', ''); | |
data[i] = parseInt(data[i]) | |
} | |
var result = data.join(', '); | |
console.log(result); | |
} | |
var input = fs.createReadStream('hostingpfids.txt'); | |
readLines(input, func); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment