I am trying to download data into JSON file from URL in nestjs but I cannot figure out how to do it.
Below is my controller function with reference to this answer.
export class DataController {
constructor(private readonly httpService: HttpService) { }
@Get()
async download(@Res() res) {
const writer = createWriteStream('user.json');
const response = await this.httpService.axiosRef({
url: 'https://api.github.com/users/prasadg',
method: 'GET',
responseType: 'stream',
headers: {
'Content-Type': 'application/json',
}
});
response.data.pipe(writer); <--- Error here: Property 'pipe' does not exist on type 'unknown'.
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}
As I mentioned above it is showing error
error TS2339: Property 'pipe' does not exist on type 'unknown'
Expected result : I want to write json data into file (user.json) in my folder on server.
How do I solve this problem?
This is just a types mistake, make sure the axios is in your project by this command:
npm i axios
Then just declare the type in your response variable
@Get()
async download() {
const writer = createWriteStream('user.json');
// response variable has to be typed with AxiosResponse<T>
const response: AxiosResponse<any> = await this.httpService.axiosRef({
url: 'https://api.github.com/users/prasadg',
method: 'GET',
responseType: 'stream',
});
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}