0

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!

asked Mar 27, 2014 at 15:31
1
  • 1
    nl++. What this does is increment nl and return the original value. Try start = ++nl. ++nl will increment nl and return the new value. Commented Mar 27, 2014 at 15:33

1 Answer 1

4

You're looking for ++nl and not nl++ , num++ increments the number and returns the old value.

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.

answered Mar 27, 2014 at 15:33
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting. I've never run into that before, thanks. Will accept in 12 minutes.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.