Search code examples
javascriptnode.jssupertest

How to attach multiple files from the same directory with supertest package in Node?


I want to attach around 100 files into a POST request using supertest, but I haven't found any way to do this.

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

Given the following piece of code, the request needs to chain the attach method every time a fileN is wanted to be send in the request, so I want how to attach recursively every file inside the same folder using the fs node core module


Solution

  • supertest extends superagent with testing functionality and works the same way. request.post('/upload') creates request instance and is chainable. Instance methods return an instance itself for chaining:

    const requestInstance = request.post('/upload');
    
    requestInstance === requestInstance.attach('file', ...);
    

    supertest and superagent are thenable, it's preferable to chain the result as a promise for correct control flow when it's used with async..await:

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