Search code examples
node.jsexpressaxiosnode-streamsnode-fetch

Piping Remote files in Node JS looking for alternative ways


I was using a request module and that is deprecated now. It was useful to pipe the remote files without storing in server. So looking for an alternative solution of the same function with Node-fetch, GOT, Axios etc..

import request from 'request';

    (req, res) { 
       return request(`http://files.com/image.jpg`)
            .on('error', (err) => {
              log.error('error fetching img url: %O', err);
              res.status(500).end('error serving this file');
            })
            .on('response', (urlRes) => {
              if (urlRes.statusCode === 304) return;
              urlRes.headers['content-disposition'] = `inline;filename="${slug}"`;
            })
            .pipe(res);
        }

Solution

  • I just tried this way with node-fetch module, it works. But it doesn't pipe the response headers as like in request module. So we need to do set the required headers manually.

    import fetch from 'node-fetch';
    (req, res) {
     fetch('http://files.com/image.jpg').then((response) => {
          res.set({
            'content-length': response.headers.get('content-length'),
            'content-disposition': `inline;filename="${slug}"`,        
            'content-type': response.headers.get('content-type'),        
          })
          response.body.pipe(res);
          response.body.on('error', () => {}) // To handle failure
        });
    }