Outsider
Outsider

Reputation: 933

callback in fs.write is not working as document

as node.js document

fs.write(fd, buffer, offset, length, position, [callback])

So I wrote like:

var fs = require('fs');

fs.open('./example.txt', 'a', 0666, function(err, fd) {
  if (err) { throw err; }
  console.log('file opened');
  fs.write(fd, 'test', null, null, null, function(err) {
    if (err) { throw err; }
    console.log('file written');
    fs.close(fd, function() {
      console.log('file closed');
    });
  });
});

but callback of fs.write is not fired. output is just 'file opended'.

fs.write(fd, 'test', null, null, function(err) {

but I assign callback for 5th parameter not 6th. this is works. Why defferent with document.

and in node source( node_file.cc ) callback is 6th parameter.

 Local<Value> cb = args[5];

I don't understand.

Upvotes: 2

Views: 4664

Answers (2)

Shenme
Shenme

Reputation: 1192

There was an older interface for fs.write that is still supported. It allowed strings to be written. Because you gave a string instead of a 'Buffer' node tried to make your arguments fit this older interface:

fs.write(fd, data, position, encoding, callback)

Notice that the older interface had 'callback' as the 5th argument. For the fifth argument you gave it 'null' :

fs.write(fd, 'test', null, null, null, function(err) {

node saw 'null' for your callback and so didn't think you had given node a callback.

Either use Buffer data strings as suggested, or use the old interface correctly to use plain strings. If you aren't ready to use Buffer's right now, just use "new Buffer('test')" until you are ready.

Upvotes: 4

Luke Girvin
Luke Girvin

Reputation: 13452

You need to pass a buffer, not a string as your second argument to fs.write. Also, the callback will be given three arguments, not one:

var buffer = new Buffer('test');
fs.write(fd, buffer, 0, buffer.length, null, function(err, written, buffer) {

From the documentation:

fs.write(fd, buffer, offset, length, position, [callback])

Write buffer to the file specified by fd.

offset and length determine the part of the buffer to be written.

position refers to the offset from the beginning of the file where this data should be written. If position is null, the data will be written at the current position. See pwrite(2).

The callback will be given three arguments (err, written, buffer) where written specifies how many bytes were written from buffer.

Finally, '0666' in the call to fs.open represents a UNIX file mode.

Upvotes: 3

Related Questions