【问题标题】:node.js file write position parameter isn't workingnode.js 文件写入位置参数不起作用
【发布时间】:2013-01-16 20:30:57
【问题描述】:

我很难让 node.js 在正确的位置写入我的文件。这是我的问题的一个示范案例:

fs = require('fs');
foo = fs.openSync('foo.txt','r+');
fs.writeSync(foo, "hello", 0, 5, 5);
fs.close(foo);

foo.txt 有一行:

12345678901234567890

预期的输出是foo.txt 包含12345hello1234567890,但我得到的是hello678901234567890。我正在运行node v0.8.16。

这是一个错误,还是我做错了什么?

编辑:我一直在参考这些文档:fs.writeSync(fd, buffer, offset, length, position)

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    正如文档链接所说,第二个参数是Buffer,但在您的代码中,您传递的是一个字符串。这样做会导致 Node 回退到为向后兼容而存在的不同函数签名。

    function(fd, str, position, encoding);
    

    所以传递正确的参数

    var buf = new Buffer("hello");
    fs.writeSync(foo, buf, 0, buf.length, 5);
    

    【讨论】:

      【解决方案2】:

      这是 Node.js 源代码所说的:

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

      如果您仔细查看第二个参数是否不是缓冲区,则 position 变为 offset 并且偏移量变为 0

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-18
        • 2018-03-24
        • 2013-12-20
        • 1970-01-01
        相关资源
        最近更新 更多