2

I am interested in using ffmpeg with node. I have looked at the many libraries available (such as fluent-ffmpeg), but they are not what I'm looking for.

I would like to know if there is a way to execute FFMPEG with node, but instead of creating a file, transfering everything to a stream. I don't want to use disc space for 'reasons' and it would make more sense for my application to execute a command and pipe that audio/video into a node stream instead.

Is there a way to do this? If so, what's my best bet?

Pedro Dalla
  • 33
  • 1
  • 6

1 Answers1

3

Yes, this is really easy as a child process.

If you use a hyphen - for an input or output filename, it will allow you to pipe with STDIN or STDOUT. Therefore, you just need to do something like this:

const ffmpeg = child_process.spawn('ffmpeg', [
  '-i', '-',
  // Some other parameters here
  '-'
]);

You can use ffmpeg.stdin and ffmpeg.stdout here.

See also: https://nodejs.org/api/child_process.html

Brad
  • 159,648
  • 54
  • 349
  • 530
  • Hey, this is really helpful, thank you so much! Also, could you provide me with some link or documentantion on where to get this information? I have been looking on the documentation for child_process and methods such as spawn() and fork() but haven't found anything about what you said. – Pedro Dalla Nov 26 '20 at 03:42
  • @PedroDalla There is a link at the end of my answer to the documentation. :-) – Brad Nov 26 '20 at 05:03
  • I get a "EPIPE" error, Im just reading via `fs.createReadStream` and pipe that into `ffmepg.stdin` any clue why? – Marc Nov 23 '21 at 19:04
  • @Marc Probably, your FFmpeg process died early. Make sure you're reading STDERR to figure out why. – Brad Nov 23 '21 at 19:58
  • @Brad it exit with status code 0, and complete every operation. It seems that juse node had a "problem" with the stdin stream. – Marc Nov 23 '21 at 20:05
  • @Marc Ah it might be the case then that you tried to write to STDIN after it closed. It's a pretty common issue I run into a lot. Sometimes, if the process dies (or, even exits cleanly) there might still be a packet of input that didn't make it. Usually, I just handle errors on STDIN to avoid my Node.js process from crashing out, and ignore those errors if the child process has exited or if I've tried to end it. – Brad Nov 23 '21 at 20:38
  • @Brand Yeah, that is what i came up with. Listen for errors (especially on ffmpeg stdin) and ignore the EPIPE error if ffmepg exit properly. Feels a bit hacky, but does the job :/ – Marc Nov 23 '21 at 20:42
  • @Marc There is some property on the stream you can check to see if it is closed before writing. I've had trouble with that in the past, but that might have been ages ago... might be worth checking out again. – Brad Nov 23 '21 at 21:22
  • @Brad Suits not 100% your problem, but has the mos of it in it: https://stackoverflow.com/a/70086772/5781499 Implement a WebSocket server & pipe a stream into stdin of the ffmpeg process. – Marc Nov 25 '21 at 13:04