如果您想将文件作为数据的持久存储以防止在系统崩溃或正在运行的进程网络中的一个成员死亡的情况下丢失流,您仍然可以继续写入文件并从中读取。
如果您不需要此文件作为 Java 进程生成的结果的持久存储,那么使用 Unix 套接字在易用性和性能方面都会好得多。
fs.watchFile() 不是您所需要的,因为它适用于文件系统报告的文件统计信息,并且由于您想读取已经写入的文件,所以这不是您想要的。
简短更新:我很遗憾地意识到,虽然我在上一段中指责 fs.watchFile() 使用文件统计信息,但我自己在下面的示例代码中做了同样的事情!虽然我已经警告读者“小心!”因为我只用了几分钟就写好了,甚至没有测试好;不过,如果底层系统支持,使用fs.watch() 代替watchFile 或fstatSync 可以做得更好。
为了从文件中读取/写入,我刚刚在下面写了一些有趣的东西:
test-fs-writer.js:[您不需要这个,因为您在 Java 进程中编写文件]
var fs = require('fs'),
lineno=0;
var stream = fs.createWriteStream('test-read-write.txt', {flags:'a'});
stream.on('open', function() {
console.log('Stream opened, will start writing in 2 secs');
setInterval(function() { stream.write((++lineno)+' oi!\n'); }, 2000);
});
test-fs-reader.js:[注意,这只是演示,检查错误对象!]
var fs = require('fs'),
bite_size = 256,
readbytes = 0,
file;
fs.open('test-read-write.txt', 'r', function(err, fd) { file = fd; readsome(); });
function readsome() {
var stats = fs.fstatSync(file); // yes sometimes async does not make sense!
if(stats.size<readbytes+1) {
console.log('Hehe I am much faster than your writer..! I will sleep for a while, I deserve it!');
setTimeout(readsome, 3000);
}
else {
fs.read(file, new Buffer(bite_size), 0, bite_size, readbytes, processsome);
}
}
function processsome(err, bytecount, buff) {
console.log('Read', bytecount, 'and will process it now.');
// Here we will process our incoming data:
// Do whatever you need. Just be careful about not using beyond the bytecount in buff.
console.log(buff.toString('utf-8', 0, bytecount));
// So we continue reading from where we left:
readbytes+=bytecount;
process.nextTick(readsome);
}
您可以安全地避免使用nextTick,而是直接调用readsome()。由于我们仍在此处进行同步,因此在任何意义上都没有必要。我只是喜欢它。 :p
编辑Oliver Lloyd
以上面的例子为例,但将其扩展为读取 CSV 数据给出:
var lastLineFeed,
lineArray;
function processsome(err, bytecount, buff) {
lastLineFeed = buff.toString('utf-8', 0, bytecount).lastIndexOf('\n');
if(lastLineFeed > -1){
// Split the buffer by line
lineArray = buff.toString('utf-8', 0, bytecount).slice(0,lastLineFeed).split('\n');
// Then split each line by comma
for(i=0;i<lineArray.length;i++){
// Add read rows to an array for use elsewhere
valueArray.push(lineArray[i].split(','));
}
// Set a new position to read from
readbytes+=lastLineFeed+1;
} else {
// No complete lines were read
readbytes+=bytecount;
}
process.nextTick(readFile);
}