Search code examples
node.jschild-processtcpdump

NodeJS: Can't read binary data from tcpdump using child_process.spawn


I can't read binary data from tcpdump -w - in NodeJS.

const {spawn} = require('child_process');
spawn('tcpdump', ['-w -']).stdout.on('data', (data) => console.log(data.toString()))

It works with text data (without -w -).

I've tried with -U and verified that the libpcap I have on my machine export pcap_dump_flush. I can see with strace that tcpdump is indeed outputting the data. If I spawn another tcpdump with -r - and attach the stdout of the first one to it the data is passed to the second tcpdump. But the stdout data listener is never called and calling stdout.read returns null.

Note: I'm aware of pcap, pcap2 and pcap-master but they don't seem to be maintained anymore and didn't compile with the latest version of node and I'd rather use tcpdump anyway.


Solution

  • It worked for me if you separate the arguments like so.

    const {spawn} = require('child_process');
    spawn('tcpdump', ['-w', '-']).stdout.on('data', (data) => console.log(data.toString()))