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.
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
Asked: 2022-01-13 11:00:00 +0000
Seen: 6 times
Last updated: Nov 20 '22