如何在nestjs中从URL将数据下载到JSON文件中



我正试图从nestjs中的URL将数据下载到JSON文件中,但我不知道如何做到这一点。

下面是我关于这个答案的控制器功能。

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);
});
}

正如我上面提到的,它显示错误

错误TS2339:类型"未知"上不存在属性"pipe">

预期结果:我想将json数据写入服务器上文件夹中的文件(user.json(中。

我该如何解决这个问题?

这只是一个类型错误,请通过以下命令确保axios在您的项目中:

npm i axios 

然后只需在响应变量中声明类型

@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);
});
}

这是未经测试的,我不确定它是否有效。但在你的代码中有一些误解,我希望能澄清并让你朝着正确的方向前进。

export class DataController {
constructor(private readonly httpService: HttpService) { }
@Get()
async download(@Res() res) {
const writer = createWriteStream('user.json');
// Here you await the result of the request
// Meaning you wait here until all the data is recieved, which is then stored in response
const response = await this.httpService.axiosRef({
url: 'https://api.github.com/users/prasadg',
method: 'GET',
responseType: 'stream',
headers: {
'Content-Type': 'application/json',
}
});
// Here you are trying to use a function called pipe on the property data on the response
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);
});
}

我想你宁愿为数据管道做这样的事情

writer.pipe(response.data);

如果你使用fs.createWriteStream,它可能看起来更像这个

writer.write(response.data);

您可能希望将请求放入流中,这样数据就可以在接收时进行流式传输,而不必等待

export class DataController {
constructor(private readonly httpService: HttpService) { }
@Get()
async download(@Res() res) {
const writer = createWriteStream('user.json');
writer.pipe(this.httpService.axiosRef({
url: 'https://api.github.com/users/prasadg',
method: 'GET',
responseType: 'stream',
headers: {
'Content-Type': 'application/json',
}
});
);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}

就像我说的,代码没有经过测试,所以你必须使用它,但希望它能让你朝着正确的方向

最新更新