Node.js 如何使用http下载文件?

Node.js 如何使用http下载文件?,node.js,express,chai,chai-http,Node.js,Express,Chai,Chai Http,这是我的问题:我必须测试一个丰富文件并使其可下载的路径。我遇到的问题是,我无法在测试期间获得丰富的文件 我设法用Axios恢复这个文件(对于终端命令),但我必须使用http进行测试 路由器.js const router=require('express').router(); const path=require('path'); const{enrichmentFileJSON}=require('../services/enrich/json'); router.post('/enrich

这是我的问题:我必须测试一个丰富文件并使其可下载的路径。我遇到的问题是,我无法在测试期间获得丰富的文件

我设法用Axios恢复这个文件(对于终端命令),但我必须使用http进行测试

路由器.js

const router=require('express').router();
const path=require('path');
const{enrichmentFileJSON}=require('../services/enrich/json');
router.post('/enrich/json',async(req,res)=>{
让{args}=req.query;
等待enrichmentFileJSON(请求,参数);
返回res.status(200).download(path.resolve(tmpDir,'experiment.jsonl'));
});
testEnrichment.js

const chai=require('chai');
const chaiHttp=require('chai-http');
常数fs=需要('fs-extra');
const path=require('path');
chai.should();
柴胡;柴胡;
常量url=http://localhost:8080';
描述('/enrich/json-enrich-a-jsonl文件',()=>{
它('应该返回丰富的文件',async()=>{
const response=wait.request(url)
.post(“/enrich/json”)
.attach('fileField',path.resolve(\uu dirname,'enrichment','file.jsonl'),'file.jsonl')
.set('Access-Control-Allow-Origin','*'))
.set('内容类型','多部分/表单数据')
//我想用这样的东西
const writer=fs.createWriteStream(path.resolve(uu dirname,'tmp','experiment.jsonl');
响应.数据.管道(编写器);
});
});
提前谢谢你

对于
“chai http”:“^4.3.0”
,调用
响应
对象上的
.buffer()
.parse()
方法以获取下载文件的缓冲区

然后,使用
stream
模块的
Readable.from(buffer)
,将缓冲区转换为可读流

例如

index.js

const express=require('express');
const multer=require('multer');
const path=require('path');
常量app=express();
var upload=multer({dest:path.resolve(uu dirname,'uploads/'))});
app.post('/enrich/json',upload.single('fileField'),async(req,res)=>{
返回res.status(200).download(path.resolve(uu dirname,'file.jsonl'));
});
module.exports=app;
index.test.js

const chai=require('chai');
const chaiHttp=require('chai-http');
常数fs=要求('fs');
const path=require('path');
const{Readable}=require('stream');
常量app=require('./');
柴胡;柴胡;
const binaryParser=函数(res,cb){
res.setEncoding('binary');
res.data='';
res.on('data',函数(块){
res.data+=块;
});
res.on('end',function(){
cb(null,Buffer.from(res.data,'binary'));
});
};
描述('66245355',()=>{
它('should pass',async()=>{
const response=wait chai
.请求(应用程序)
.post(“/enrich/json”)
.attach('fileField',path.resolve('file.jsonl'),'file.jsonl')
.set('内容类型','多部分/表单数据')
.buffer()
.parse(二进制解析器);
const writer=fs.createWriteStream(path.resolve(uu dirname,'experized.jsonl'));
可读的.from(response.body.toString()).pipe(writer);
});
});
file.jsonl
,尝试上载的文件:

{
“ok”:正确
}
experiment.jsonl
,您充实并下载的文件:

{
“ok”:正确
}

出现了什么错误?response.data未定义,我找不到要下载的文件在响应中的位置。非常感谢:)为什么使用fs.createWriteStream而不是fs.writeFileSync?