I am new to node.js so bear with me. I need to have a function that returns the line length of a file. I am hoping to do something like
file1 = line_length_func('file');
file2 = line_length_function('file');
if (file1 === file2) { console.log('same number of lines!');}
I have been looking into all sorts of ways to do so, with child.exec(cat file | wc -l) but spawning a child instance gets a bit complicated. I wasn't sure how to pass variables from my child to the parent or if is good practice to do so...
So I tried this - I saw that fd from fs.open returned the number of lines:
function get_lines(file) {
var lines = fs.open(file, 'r', function(err, fd) {
var lines = fd;
});
}
a = get_lines('file.txt');
console.log(a);
but I just get undefined all the time.
The next thing I tried is: (thanks to Andrey Sidorov's post)
function get_line_count(file) {
var count = 0;
fs.createReadStream(file)
.on('data', function(chunk) {
for (var i = 0; i < chunk.length; i++)
if (chunk[i] == 10) count++;
})
.on('end', function() {
return count;
});
}
var file1_lines = get_line_count('test.txt');
console.log(file1_lines);
but I get the same result. Undefined.
I am not used to node yet so any help would be wonderful! Thanks!
update
the line count seems to work now but I still can't write a function that compares the two.
function get_line_count(file, cb) {
var count = 0;
fs.createReadStream(file)
.on('data', function(chunk) {
for (var i = 0; i < chunk.length; i++)
if (chunk[i] == 10) count++;
})
.on('end', function() {
cb(null, count);
})
.once('error', cb);
}
var file1 = get_line_count('test.txt', function(err, lines) {
if (err) return; // todo
return lines;
});
var file2 = get_line_count('test2.txt', function(err, lines) {
if (err) return; //todo
return lines;
});
function same_line_length(len1, len2) {
return len1===len2;
}
console.log(same_line_length(file1, file2));
this is always returning true...