Javascript 如何使用节点中的supertest包从同一目录附加多个文件?
我想使用将大约100个文件附加到POST请求中,但我还没有找到任何方法Javascript 如何使用节点中的supertest包从同一目录附加多个文件?,javascript,node.js,supertest,Javascript,Node.js,Supertest,我想使用将大约100个文件附加到POST请求中,但我还没有找到任何方法 const supertest = require('supertest); const fs = require('fs'); const { promisify } = require('utils'); const request = supertest('http://localhost:3000'); const readdir = promisify(fs.readdir); (async () =>
const supertest = require('supertest);
const fs = require('fs');
const { promisify } = require('utils');
const request = supertest('http://localhost:3000');
const readdir = promisify(fs.readdir);
(async () => {
try {
const files = await readdir(path.resolve(__dirname, '/path/to');
request
.post('/upload')
.attach('file', files)
.end((response => {
console.log(response);
});
} catch(err) => {
console.error(err);
}
)();
给定以下代码段,每次请求中要发送文件时,请求都需要链接attach方法,因此,我想知道如何使用fs节点核心模块递归地附加同一文件夹中的每个文件。您可能只想使用supertest和Promise.all发出几个单独的请求。您可以使用globby来获取文件列表,例如,如果不使用async,则可能更简单,除非您需要其他地方的结果
const files = glob(path.resolve(__dirname, '/path/to'));
const requests = files.map((file) => {
return request
.post('/upload')
.attach('file', file)
.end((response => {
console.log(response);
});
});
Promise.all(requests).then(console.log('done')).catch(console.error);
supertest
扩展了superagent
的测试功能,并以相同的方式工作request.post('/upload')
创建请求实例并可链接。实例方法返回用于链接的实例本身:
const requestInstance = request.post('/upload');
requestInstance === requestInstance.attach('file', ...);
supertest
和superagent
是可以的,最好将结果链接起来,作为在与async.wait一起使用时正确控制流的承诺:
try {
const files = await readdir(path.resolve(__dirname, '/path/to');
let requestInstance = request.post('/upload');
for (const file of files) {
// no need to reassign requestInstance because it's same instance
// requestInstance = requestInstance.attach('file', file);
requestInstance.attach('file', file);
}
const response = await requestInstance;
} catch (err) {
console.error(err);
}
请提供一些您试图实现的代码示例。我让自己更清楚了一点使用fs
从fixture目录获取文件列表?@estus的可能重复不是真正的问题,我的意思是,我已经这样做了,但目标是如何实现在一个HTTP请求中传递文件数组,因为文档没有提供递归方式。。。所以我希望有两件事,一件是有人以前已经面对过,另一件是这种方法正在使用承诺!!!,我很抱歉在接下来的几个小时内不会涉及代码,但是你的解释很有道理,我很确定这会起作用,当我进行修改时,我会告诉你。。。在实例上使用wait是我遗漏的部分是的,请求是可以的是非常方便的。如果缺少supertest引用,请检查superagent文档,前者是后者的简单包装器。希望这有帮助。