Javascript 使用fs.open和fs.write以独占方式写入文件
我正在编写一个对象,该对象公开了一个函数,该函数在文件末尾追加一个字符串,以确保: 1-文件立即写入。 2-程序对文件具有独占锁定。 3-写入之间的锁是持久的 我使用fs.open fs.write和buffer,因为流看起来太复杂了。如果使用流,我假设在写入之后必须刷新 是否可以在没有大多数选项的情况下调用fs.write()和fs.writeSync()Javascript 使用fs.open和fs.write以独占方式写入文件,javascript,node.js,io,buffer,fs,Javascript,Node.js,Io,Buffer,Fs,我正在编写一个对象,该对象公开了一个函数,该函数在文件末尾追加一个字符串,以确保: 1-文件立即写入。 2-程序对文件具有独占锁定。 3-写入之间的锁是持久的 我使用fs.open fs.write和buffer,因为流看起来太复杂了。如果使用流,我假设在写入之后必须刷新 是否可以在没有大多数选项的情况下调用fs.write()和fs.writeSync() /* What I would like to do is this: */ buffer = new Buffer( string,
/* 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标志): 如果使用fs.write()而不是fs.writeSync(),则此代码不能始终保证“Hello World!”将在“再见世界!”之前编写。我对此进行了广泛的测试,只有一次订单错误。我插入了一系列大小为s/(2^n)的块,因此第一个块是256kb,下一个是128kb,下降到1kb,在一次试运行中,第一个块是最后插入的,而不是第一个,所有其他块都是有序的。在整个测试过程中,区块完整性也得到了保持。根据硬件、软件和负载的不同,结果可能会有所不同。出于日志记录的目的,不按顺序排列并不可怕,因为每个块都可以(而且应该)加上时间戳 显而易见的是:
你的目的是什么?您可以改为尝试fs.writeFile或fs.WriteStream。在Node.JS文档中,“[]”内的参数是可选的,因此这些参数不是必需的,也是必需的。我正在写入日志文件,希望以独占方式访问它。
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();