简体   繁体   English

使用fs.open和fs.write专门写入文件

[英]Using fs.open and fs.write to write exclusively to a file

I am writing an object that exposes a function that appends a string to the end of a file ensuring that: 我正在编写一个公开一个函数的对象,该函数将一个字符串附加到文件的末尾,以确保:

1- file is written to immediately. 1-文件立即写入。 2- the program has an exclusive lock on the file. 2-程序对文件具有独占锁定。 3- the lock is persistent between writes 3-锁定在写入之间是持久的

I am using fs.open fs.write and buffer, because Streams seem too complicated. 我正在使用fs.open fs.write和buffer,因为Streams看起来太复杂了。 I assume I would have to flush after a write if I used a stream. 我假设如果我使用了一个流,我必须在写入后刷新。

Is it possible to call fs.write() and fs.writeSync() without most of the options. 是否可以在没有大多数选项的情况下调用fs.write()和fs.writeSync()。

/* What I would like to do is this: */

buffer = new Buffer( string, encoding );
fs.write( fd, buffer, callback );
fs.writeSync( fd, buffer );

// Failing that I would like to know which of these is correct:

fs.write( fd, buffer, 0, buffer.length, null, callback );
fs.write( fd, buffer, 0, string.length, null, callback );

Ok so I did some testing and came up with the following code, which assumes the file doesn't exist (it will throw an exception because of the x flag if it does): 好的,所以我做了一些测试并提出了以下代码,它假设该文件不存在(如果有的话,它将因为x标志而抛出异常):

var fs = require("fs");
var log = {

    filename: "path",
    flag: "ax",
    mode: 0444,
    file: null,
    encoding: "utf8",
    finalMode: 0644,

    write: function( string ) {
        if( this.file == null ) {

            this.file = fs.openSync(this.filename, this.flag, this.mode);

        }
        if( string instanceof String ) string = string.toString();
        if( typeof string != "string" ) string = JSON.stringify( string );
        var buffer = new Buffer( string, this.encoding );
        fs.writeSync(this.file, buffer, 0, buffer.length);
        return this;
    },
    close: function() {
        fs.close(this.file);
        if( this.finalMode != this.mode ) {
            fs.chmod(this.filename, this.finalMode);
        }
        return this;
    }
}

log.write("Hello World!\n").write("Goodbye World!\n").close();

This code can't always guarantee "Hello World!" 这段代码不能总是保证“Hello World!” would be written before "Goodbye World!" 将在“再见世界”之前写出来! if fs.write() is used instead of fs.writeSync(). 如果使用fs.write()而不是fs.writeSync()。 I have tested this extensively and have only had one occasion where the order was wrong. 我已经对此进行了广泛的测试,并且只有一次订单错误。 I inserted a sequence of chunks with size s/(2^n) so the first chunk was 256kb and the next 128kb down to 1kb and in one trial run the first chunk was inserted last instead of first and all the other chunks were in order. 我插入了一系列大小为s /(2 ^ n)的块,所以第一个块是256kb,接下来的128kb是1kb,在一次试运行中,第一个块最后插入而不是第一块,所有其他块都按顺序插入。 Chunk integrity was preserved as well throughout the tests. 在整个测试过程中也保留了块完整性。 Results may differ on your system based on hardware, software and load. 基于硬件,软件和负载,您的系统的结果可能会有所不同。 For logging purposes not being in order is not terrible as each chunk can (and should) be prepended with a timestamp. 对于日志记录目的而言,不按顺序并不可怕,因为每个块都可以(并且应该)添加时间戳。

What is clear is that: 很清楚的是:

  1. Offset and length are required and will cause exceptions if left empty. 偏移和长度是必需的,如果留空则会导致异常。
  2. Offset and length are in bytes. 偏移量和长度以字节为单位。
  3. Buffer.length must be used, like in the question's first example. 必须使用Buffer.length,就像在问题的第一个例子中一样。 Even though most of the time string.length == buffer.length if encoding is utf8 it is better not to use the second example. 尽管大多数时候string.length == buffer.length如果编码是utf8,最好不要使用第二个例子。
  4. Position can be undefined (not provided in the function call) and will behave as if null (no strong equality in the function) 位置可以是未定义的(在函数调用中未提供),并且将表现为null(函数中没有强相等性)
  5. Callback can be undefined (as specified in documentation) 回调可以是未定义的(如文档中所指定)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM