I'm having a hard time getting node.js to write to my file at the correct position. Here's a demonstrative case of my problem:
fs = require('fs');
foo = fs.openSync('foo.txt','r+');
fs.writeSync(foo, "hello", 0, 5, 5);
fs.close(foo);
foo.txt has one line:
12345678901234567890
The expected output is for foo.txt to contain 12345hello1234567890, but instead I'm getting hello678901234567890. I'm running node v0.8.16.
Is this a bug, or am I doing something wrong?
EDIT: I've been referencing these docs: fs.writeSync(fd, buffer, offset, length, position)
As the link to the docs say, the 2nd argument is a Buffer, but in your code you are passing a string. Doing this is causing Node to fall back to a different function signature that exists for backwards-compatability.
function(fd, str, position, encoding);
So pass the proper arguments
var buf = new Buffer("hello");
fs.writeSync(foo, buf, 0, buf.length, 5);
Here it is what Node.js source code says:
lib\fs.js
fs.writeSync = function(fd, buffer, offset, length, position) {
if (!Buffer.isBuffer(buffer)) {
// legacy string interface (fd, data, position, encoding)
position = arguments[2];
buffer = new Buffer('' + arguments[1], arguments[3]);
offset = 0;
length = buffer.length;
}
if (!length) return 0;
return binding.write(fd, buffer, offset, length, position);
};
If you look carefully if the second argument is not a buffer the position become offset and the offset become 0