Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js file write position parameter isn't working

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)

like image 942
perimosocordiae Avatar asked Jan 16 '13 20:01

perimosocordiae


People also ask

How do you write data to a file in node JS?

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.

What is the difference between writeFile and writeFileSync?

The only difference between writeFile and writeFileSync is in catching and handling the errors; otherwise, all parameters mentioned are available in both functions.

What is __ Dirname NodeJs?

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.


2 Answers

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);
like image 112
loganfsmyth Avatar answered Oct 11 '22 01:10

loganfsmyth


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

like image 3
Emil Condrea Avatar answered Oct 10 '22 23:10

Emil Condrea