So for some reason, when I use the increment operator in this code, it doesn't work. I've verified my variables are numbers.. Not sure what's going on.
var fs = require('fs')
, bt = require('buffertools')
var start = 0;
fs.readFile(process.argv[2], function(err, data) {
console.log(data);
while (bt.indexOf(data, '\n', start)) {
var nl = bt.indexOf(data, '\n', start); // nl is 40
console.log(start, nl); // 0, 40
console.log(data.slice(start, nl)); // works great!
start = nl++; // reset the offset past that last character..
console.log(start, typeof start); // start == 40? the heck? 'number'
process.exit(); // testing
//console.log(nl, start); 40, 40
}
});
EDIT ------
And the solution...
"use strict";
var fs = require('fs')
, bt = require('buffertools');
fs.readFile(process.argv[2], function(err, data) {
var offset = 0;
while (true) {
var nl = bt.indexOf(data, '\n', offset);
if (nl === -1) break;
console.log(data.slice(offset, nl));
offset = ++nl;
}
console.log(data.slice(offset));
});
Thanks!
1 Answer 1
You're looking for ++nl and not nl++ , num++ increments the number and returns the old value.
num++is the postfix increment operator - as you can see, its description says "Return oldValue."++numis the prefix incremenet operator - as you can see, its description says "Return newValue."
This is true in many other languages too by the way.
Since you're not changing nl later at all, you can write this as:
start = nl + 1;
Which is clearer.
nl++. What this does is incrementnland return the original value. Trystart = ++nl.++nlwill incrementnland return the new value.