I want to read all bytes in file A, subtract 0x80 from each byte, and write the results to file B.
Here's some pseudocode:
try:
open file A for reading
open file B for writing
loop until EOF:
x = next byte from file A
x = x - 0x80;
write x to file B
finally:
close file A
close file B
How can this be done in node.js using the asynchronous file system functions?
I gave it a shot, but gave up when my code got half a dozen levels deep with callbacks and exception handling. Please teach me clean asynchronous programming. :)
"but gave up when my code got half a dozen levels deep with callbacks and exception handling"...
that's called "callback hell", and it is inherent to async programming.
You can use wait.for, a very simple lib I've developed recently, to program sequentially (as in your pseudocode) avoiding callback hell. check: http://github.com/luciotato/waitfor
You can also google "nodejs promises", https://github.com/kriskowal/q and "nodejs async lib", https://github.com/caolan/async but consider that promises and async libs add complexity in order to ease the pain of callback hell (they also provide a lot of functionality, but, at the expense of adding new concepts and more complexity).
Note: In the specific case of your example, core node 'fs' module- http://nodejs.org/api/fs.html - makes an exception to "nothing should block in node" and eases callback hell by providing two versions of almost every function, one standard async and another one blocking *Sync.