[英]Using fs.open and fs.write to write exclusively to a file
我正在編寫一個公開一個函數的對象,該函數將一個字符串附加到文件的末尾,以確保:
1-文件立即寫入。 2-程序對文件具有獨占鎖定。 3-鎖定在寫入之間是持久的
我正在使用fs.open fs.write和buffer,因為Streams看起來太復雜了。 我假設如果我使用了一個流,我必須在寫入后刷新。
是否可以在沒有大多數選項的情況下調用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 );
好的,所以我做了一些測試並提出了以下代碼,它假設該文件不存在(如果有的話,它將因為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();
這段代碼不能總是保證“Hello World!” 將在“再見世界”之前寫出來! 如果使用fs.write()而不是fs.writeSync()。 我已經對此進行了廣泛的測試,並且只有一次訂單錯誤。 我插入了一系列大小為s /(2 ^ n)的塊,所以第一個塊是256kb,接下來的128kb是1kb,在一次試運行中,第一個塊最后插入而不是第一塊,所有其他塊都按順序插入。 在整個測試過程中也保留了塊完整性。 基於硬件,軟件和負載,您的系統的結果可能會有所不同。 對於日志記錄目的而言,不按順序並不可怕,因為每個塊都可以(並且應該)添加時間戳。
很清楚的是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.