Ask Your Question
4

How can I convert a file from an external link to a buffer using Nest.js?

asked 2022-01-13 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-11-20 07:00:00 +0000

devzero gravatar image

To convert a file from an external link to a buffer using Nest.js, you can use the built-in http or https module in Node.js to make a GET request to the external link and then convert the response data into a buffer using the Buffer.from() method. Here's an example implementation:

import { Injectable } from '@nestjs/common';
import { http, https } from 'follow-redirects';
import { Buffer } from 'buffer';

@Injectable()
export class FileService {
  async getFileFromURL(url: string): Promise<Buffer> {
    const isHTTPS = url.startsWith('https://');
    const client = isHTTPS ? https : http;
    return new Promise<Buffer>((resolve, reject) => {
      const req = client.get(url, (res) => {
        const chunks = [];
        res.on('data', (chunk) => chunks.push(chunk));
        res.on('end', () => {
          const buffer = Buffer.concat(chunks);
          resolve(buffer);
        });
      });
      req.on('error', (err) => reject(err));
    });
  }
}

Here, we define a getFileFromURL method in a FileService class that takes a URL string as input and returns a Promise that resolves to a buffer. In the method, we first check whether the URL starts with https:// or http:// and use the respective Node.js module to make a GET request to the URL. We then listen for the response data event and push each chunk of data into an array. When the response end event is emitted, we concatenate all the data chunks into a single buffer using Buffer.concat() and resolve the Promise with it. If there's an error during the request, we reject the Promise with the error object.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-13 11:00:00 +0000

Seen: 12 times

Last updated: Nov 20 '22