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)
The fs. writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The 'options' parameter can be used to modify the functionality of the method.
The only difference between writeFile and writeFileSync is in catching and handling the errors; otherwise, all parameters mentioned are available in both functions.
It gives the current working directory of the Node. js process. __dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With