【问题标题】:callback in fs.write is not working as documentfs.write 中的回调不能作为文档工作
【发布时间】:2011-12-03 12:26:46
【问题描述】:

作为 node.js 文档

fs.write(fd, 缓冲区, 偏移量, 长度, 位置, [回调])

所以我这样写:

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');
    });
  });
});

但是 fs.write 的回调没有被触发。输出只是“文件打开”。

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

但我为第 5 个参数而不是第 6 个参数分配回调。这是作品。 为什么与文档不同。

并且在节点源(node_file.cc)回调是第6个参数。

 Local<Value> cb = args[5];

我不明白。

【问题讨论】:

  • fs.open 中的 0666 是什么意思?

标签: node.js


【解决方案1】:

仍然支持 fs.write 的旧接口。它允许写入字符串。因为你给了一个字符串而不是一个“缓冲区”节点试图让你的参数适合这个旧接口:

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

请注意,旧接口将“回调”作为第 5 个参数。对于第五个参数,你给它'null':

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

node 看到您的回调为“null”,因此认为您没有给 node 一个回调。

要么按照建议使用缓冲区数据字符串,要么正确使用旧接口来使用纯字符串。如果你现在还没有准备好使用 Buffer,只要使用 "new Buffer('test')" 直到你准备好。

【讨论】:

    【解决方案2】:

    您需要将buffer,而不是字符串作为第二个参数传递给 fs.write。此外,回调将被赋予三个参数,而不是一个:

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

    来自documentation

    fs.write(fd, 缓冲区, 偏移量, 长度, 位置, [回调])

    将缓冲区写入fd指定的文件。

    偏移量和长度决定了要写入的缓冲区部分。

    position 是指从文件开头的偏移量,应该写入该数据。如果 position 为 null,则数据将写入当前位置。请参阅 pwrite(2)。

    回调将被赋予三个参数(err、written、缓冲区),其中written 指定从缓冲区写入的字节数。

    最后,fs.open 调用中的“0666”代表UNIX file mode

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 2017-12-31
      相关资源
      最近更新 更多