在 node.js 中读取文件,同时它被另一个软件打开以供写入 [英] Read file in node.js while it is opened for writing by another software

查看:22
本文介绍了在 node.js 中读取文件,同时它被另一个软件打开以供写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:1. 一个应用程序(不是 node.js)将数据写入某个文件,大小未知2. Node.js 应该管道该文件的内容,直到它被第一个应用程序打开以进行写入.

Situation: 1. One app (not node.js) writes data to some file, size is unknown 2. Node.js should pipe contents of that file until it is opened for writing by the first app.

有可能吗?

推荐答案

你有一些解决方案.

writeStream.js 是一个简单的测试类,写在文件中作为演示

writeStream.js is a simple test class to write in the file as demo

const fs = require('fs')
const fd = fs.openSync('./openedFile.txt', 'w+')
const stream = fs.createWriteStream(null, {
  fd,
  encoding: 'utf8'
})
process.stdin.pipe(stream)

readStream 轮询:这很简单,读取流在到达文件末尾 (EOF) 时始终关闭,并且会触发结束"事件.因此,如果您全部阅读,则无法将打开的 fd 保留到文件中.(在这个例子中,我不管理流是否仍然打开,因为它无法读取所有文件)

readStream polling: this is simple, the read stream is always closed when it reaches the end of file (EOF) and a 'end' event is fired. So you can't keep an open fd to a file if you read it all. (in this example I don't manage if the stream is still open because it could not have read all the file)

const fs = require('fs')
let streamed = 0
function readFd() {
  const fd = fs.openSync('./openedFile.txt', 'r')
  const stream = fs.createReadStream(null, {
    fd,
    encoding: 'utf8',
    start: streamed
  })
  stream.on('data', function (chunk) {
    streamed += chunk.length;
  })
  stream.pipe(process.stdout)
}

setInterval(readFd, 1000)

readStream via tail(tail 命令将为您轮询)

readStream via tail (tail command will poll for you)

const { spawn } = require('child_process');
const child = spawn('tail', ['-f', 'openedFile.txt']);
child.stdout.pipe(process.stdout)

这篇关于在 node.js 中读取文件,同时它被另一个软件打开以供写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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