Node.js nested function scoping question -> fetching data stream piping to a file

Viewed 60

This works and pipes downloaded data into a file:

const fs = require('fs')
await fetch(downloadURL).then(res => {
        const dest = fs.createWriteStream('/tmp/output.xlsx');
        res.body.pipe(dest);
});

This also works:

    const buffer = await page.evaluate(({downloadURL}) =>
    {
      return fetch(downloadURL, {
        method: 'GET'
      }).then(r => r.text());
    }, {downloadURL});

But to read a binary stream inside of page.evaluate(), I need to replace r => r.text() with the res.body.pipe from the first code snipped. When I do that:

    const fs = require('fs')
    const buff = await page.evaluate(({ downloadURL, fs }) => {
      return fetch(downloadURL, fs, {
        method: 'GET'
      }).then(res => {
        const dest = fs.createWriteStream('/tmp/output.xlsx');
        res.body.pipe(dest);
      });
    }, { downloadURL, fs });

The error I get is TypeError: fs.createWriteStream is not a function

I don't think it has anything to do with "fs" per se; my bet is that somehow the "fs" is out of scope for this function structure.

How do I fix this last snippet so the data read is piped to a file?

My gut tells me it's some syntactical fix someone more skilled than I am can do...

thx

0 Answers
Related