fs.createWriteStream通过多个进程 [英] fs.createWriteStream over several processes

查看:104
本文介绍了fs.createWriteStream通过多个进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何实现一个系统,其中多个Node.js进程使用 fs.createWriteStream 写入同一文件,以使它们不会覆盖数据?看起来fs.createWriteStream的默认设置是在调用该方法时清除该文件.我的目标是清除一次文件,然后让所有其他后续写入器仅附加数据.

How can I implement a system where multiple Node.js processes write to the same file with fs.createWriteStream, such that they don't overwrite data? It looks like the default setup for fs.createWriteStream is that the file is cleared out when that method is called. My goal is to clear out the file once, and then have all other subsequent writers only append data.

我应该先使用 fs.createWriteStream ,然后再使用 fs.appendFile 吗?还是有一种方法可以为每个进程打开流,而不仅仅是为打开文件的第一个进程打开流?

Should I use fs.createWriteStream and then fs.appendFile? Or is there a way to open up a stream for each process, not just for the first process to open the file?

推荐答案

我应该使用fs.createWriteStream然后使用fs.appendFile吗?

Should I use fs.createWriteStream and then fs.appendFile?

您可以使用其中任何一个.

you can use either.

使用fs.createWriteStream,您必须像这样更改标志:

with fs.createWriteStream you have to change the flag like this:

fs.createWriteStream('your_file',{
  flags: 'a+', // default is 'w' (just 'a' might be enough here, i'm not sure)
})

如果文件不存在,则应创建该文件;如果文件存在,则应使用写访问权将其打开,并将指针设置为end.(附加模式)

this should create the file if it doesn't exist or open it with write access if it exists and set the pointer to end. (append mode)

如何使用 fs.appendFile 应该很清楚,并且几乎一样.

How to use fs.appendFile should be clear and it does pretty much the same.

现在有多个进程访问同一文件的问题.显然,只有一个进程可以同时打开具有写访问权的同一文件.因此,如果另一个进程具有写访问权,则需要等待文件被释放.您可能需要一个库.

Now the problem with multiple processes accessing the same file. Obviously only one process can open the same file with write access at the same time. Therefore you need to wait for the file to be released if another process has the write access. You will probably need a library for that.

此示例,例如: https://www.npmjs.com/package/lockup
或这一个: https://github.com/Perennials/mutex-node
您还可以在此处找到更多信息: https://www.npmjs.com/browse/关键字/锁定
或此处: https://www.npmjs.com/browse/keyword/mutex

我还没有尝试过这些库中的任何一个,但是我发布的库和列表中的其他几个库都可以完全满足您的需求.

I have not tried any of those libraries but the one I posted and several others on the list should do exactly what you need.

这篇关于fs.createWriteStream通过多个进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆