Rayrun

How do I upload a file using the fs module in JavaScript?

Answer

To upload a file using the fs module in JavaScript, you can use the createReadStream method to open a file as a stream and pass it to the request. Here's an example of uploading a CSV file to an API endpoint at https://ray.run/api/uploadTeamList:

import fs from 'fs';
import { request } from '@playwright/test';

const stream = fs.createReadStream('team.csv');
await request.post('https://ray.run/api/uploadTeamList', { multipart: { fileField: stream } });

If you want to pass the file content directly as an object, use an object with name, mimeType, and buffer properties:

await request.post('https://ray.run/api/uploadScript', {
  multipart: {
    fileField: {
      name: 'f.js',
      mimeType: 'text/javascript',
      buffer: Buffer.from('console.log(2022);')
    }
  }
});

In both cases, use the multipart option to specify that you're sending a multipart/form-data encoded message body. The fileField property specifies the field in the form data containing the uploaded file.

For regular post data (e.g., JSON or url-encoded form data), use the data or form options:

await request.post('https://ray.run/api/createBook', {
  data: {
    title: 'Book Title',
    author: 'John Doe'
  }
});

await request.post('https://ray.run/api/findBook', {
  form: {
    title: 'Book Title',
    author: 'John Doe'
  }
});

In summary, to upload a file using the fs module in JavaScript, open a read stream on one end and pass it as a multipart/form-data encoded message body to the other end. Alternatively, send regular post data using the data or form options.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.