Relatively new with Node. Trying to work with streams.
I am looking to read from and sort a large file containing numbers (newline separated). I have sorted my file as per the the method here (method #5, referenced in this thread actually), and am trying to tweak it to return the first X lines from the sorted data (var request = 5
in the code below just for testing). I would like to display these this after writing the data.
var fs = require('fs'),
util = require('util'),
spawn = require('child_process').spawn,
sort = spawn('sort', ['-nr','../data/data.txt']),
writer = fs.createWriteStream('output.txt');
var start = Date.now();
var output = 'output.txt';
var request = 5;
var lineCount = 0;
var numbers;
var selection = [];
sort.stdout.on('data', function(data) {
lineCount ++
numbers = data.toString()
// data.toString()
.split('\n')
.sort((a, b) => b-a)
selection = numbers.slice(0, request)
//
// .forEach(record => writer.write(record + '\n'))
},
)
sort.on('exit', function(code) {
if (code) {
// handle error
console.log(code);
}
// writer.end()
// console.log(lineCount);
let array = numbers.slice(0, request);
console.log(selection);
var closetime = Date.now();
console.log('Time. ', (closetime -start) /1000, ' secs');
});
sort.stderr.on('data', function(data) {
// handle error...
console.log('stderr: ' + data);
});
I can't get it to work regardless of whether I put my code in the .on('data'
section, or in the .on('exit'
section. Any suggestions?
I did reference a large number of threads here on Stack Overflow, including this one, this one, this one on reading a specific line via nodejs, reading the first two lines via Nodejs.
This last one sounds like it should be what i need, but I can't get it to work within my code.