1

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.

Is it possible?

Lisio
  • 1,571
  • 2
  • 15
  • 22

1 Answers1

5

You have some solution.

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 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 command will poll for you)

const { spawn } = require('child_process');
const child = spawn('tail', ['-f', 'openedFile.txt']);
child.stdout.pipe(process.stdout)
Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
  • I think this might help me with my problem, hope you don't mind me asking a few question. process.stdout, is that data of the file being read? would you be able to emit that using socket.io-client? if yes, how would I go about doing that? placing the io.emit() inside the pipe() doesn't seem to be the proper way – blah Apr 08 '22 at 05:46
  • Could you open a new question adding your code? I'm not a socket.io user and a starting code would help me to give it a try – Manuel Spigolon Apr 08 '22 at 07:34
  • Sorry I can't post questions anymore. But if it helps I'll explain it in more details here. I'm trying to send an audio file that's still being written (using https://github.com/gillesdemey/node-record-lpcm16) to an API using socket.io-client (similar to this docu https://docs.marsview.ai/realtime-speech-analytics-api/initiate-stream). I was wondering if I could use your code to read what's being written and send it to the API – blah Apr 08 '22 at 08:03