简体   繁体   English

使用Node.js中的可写流指定写入文件的位置

[英]Specify position to write to a file using Writable Stream in nodejs

I want to write to a file multiple times using the Writable Stream in nodejs. 我想使用nodejs中的可写流多次写入文件。 The problem is that I also want to specify the postion also to this writer. 问题是我也想向作者指定位置。

Here is some background - I want to create a multi threaded downloader. 这是一些背景-我想创建一个多线程下载器。 The data which comes as a response needs to be saved to the disk. 作为响应而来的数据需要保存到磁盘上。 The order of the data chunks can be random and that is why I need to pass the position parameter also to the writeable stream. 数据块的顺序可以是随机的,这就是为什么我需要将position参数也传递给可写流的原因。

I am using writable stream instead of fs.write because the documentation says so - 我使用的是可写流而不是fs.write,因为文档说的是-

Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. 请注意,不等待回调就在同一文件上多次使用fs.write是不安全的。 For this scenario, fs.createWriteStream is strongly recommended. 对于这种情况,强烈建议使用fs.createWriteStream。

Thanks! 谢谢!

You can do this using the start option, however, it requires the file exist and have a size >= offset + chunkToWrite.length. 您可以使用开始选项来执行此操作,但是,它要求文件存在并且大小> = offset + chunkToWrite.length。 This would put you back to using fs.writeFile with some dummy contents whose size is >= the size of the file to be downloaded, and needing to wait for the callback from that initial write. 这将使您重新使用fs.writeFile和一些虚拟内容,这些虚拟内容的大小大于等于要下载的文件的大小,并且需要等待该初始写入的回调。 For example: 例如:

var buffer = new Buffer (fileSize);
buffer.fill('0');

fs.writeFile('./file', buffer, function() {
  var writeStream = fs.createWriteStream('./file',{flags: 'r+', mode: 0777, start: 10});
  writeStream.write('HELLO AFTER 10');
});

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

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