13

The fs.createReadStream() and fs.createWriteStream() only support file paths but I need to read (or write) from a file descriptor (passed to/from a child process).

Note I need Streams, so fs.open/fs.read/fs.write are not sufficient.

Bartvds
  • 3,340
  • 5
  • 30
  • 42

2 Answers2

22

When you call fs.createReadStream you can pass in a file descriptor:

var fs = require('fs');
var fd = fs.openSync('/tmp/tmp.js', 'r');
var s = fs.createReadStream(null, {fd: fd});
s.pipe(process.stdout);

If there is a fd option, the filename is ignored.

Joe Hildebrand
  • 10,354
  • 2
  • 38
  • 48
  • 3
    Excellent! I found the reverse also works, with `fs.createWriteStream(null, {fd: fd});`. Weird this is not documented in the manual, but it works like a charm. – Bartvds Jul 05 '14 at 05:55
  • 1
    If you stare carefully at the doc I linked to, you see that it's at least hinted at in the docs, although I admit that I found it in the source. :) – Joe Hildebrand Jul 07 '14 at 08:56
  • Yea, but all the other fs methods have spceial versions for file descriptors. I did notice the fd param but nothing suggest you could use null as path. Odd that. – Bartvds Jul 08 '14 at 12:48
  • 3
    You need to pass empty string like this `fs.createReadStream('', {fd: fd})` instead of `null`. – Vad Jun 03 '15 at 11:56
  • 4
    LOL "stare carefully" – Alexander Mills Nov 15 '16 at 22:18
4
// Open &3:
process.oob1 = fs.createWriteStream(null, { fd: 3 });
// Write to &3 / oob1 (out-of-band 1)
process.oob1.write("Note: this will throw an exception without 3>&1 or something else declaring the existence of &3");
Fordi
  • 2,798
  • 25
  • 20