CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-form-data

A library to create readable multipart/form-data streams for form and file uploads.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

http-submission.mddocs/

HTTP Submission

Direct HTTP submission capabilities with automatic header management, content-length calculation, and support for both HTTP and HTTPS protocols.

Capabilities

Submit Method

Submits the form to a web application using Node.js HTTP/HTTPS modules.

/**
 * Submit the form to a web application
 * @param params - URL string or options object
 * @param callback - Optional callback function
 * @returns HTTP ClientRequest object for further manipulation
 */
submit(
  params: string | SubmitOptions,
  callback?: (error: Error | null, response: http.IncomingMessage) => void
): http.ClientRequest;

interface SubmitOptions extends http.RequestOptions {
  /** Protocol to use - defaults to 'http:' */
  protocol?: 'https:' | 'http:';
  /** Target hostname */
  host?: string;
  /** Target path */
  path?: string;
  /** Target port - defaults to 80 for HTTP, 443 for HTTPS */
  port?: number;
  /** HTTP method - defaults to 'post' */
  method?: string;
  /** Additional headers to send */
  headers?: { [key: string]: string };
  /** HTTP basic authentication in format 'username:password' */
  auth?: string;
}

Usage Examples:

const FormData = require('form-data');
const fs = require('fs');

const form = new FormData();
form.append('file', fs.createReadStream('document.pdf'));
form.append('title', 'Important Document');

// Simple URL submission
form.submit('http://example.com/upload', (err, res) => {
  if (err) {
    console.error('Upload failed:', err);
    return;
  }
  console.log('Status:', res.statusCode);
  res.resume(); // Drain response
});

// Advanced options
form.submit({
  host: 'api.example.com',
  path: '/v1/files/upload?folder=documents',
  protocol: 'https:',
  port: 443,
  headers: {
    'Authorization': 'Bearer token123',
    'X-Client-Version': '1.0.0'
  },
  auth: 'username:password'
}, (err, res) => {
  if (err) throw err;
  console.log('Upload completed:', res.statusCode);
});

// Without callback - handle events manually
const request = form.submit('https://httpbin.org/post');

request.on('response', (response) => {
  console.log('Response status:', response.statusCode);
  console.log('Response headers:', response.headers);
  
  let body = '';
  response.on('data', (chunk) => body += chunk);
  response.on('end', () => {
    console.log('Response body:', body);
  });
});

request.on('error', (err) => {
  console.error('Request error:', err);
});

URL Parsing

When passing a URL string, Form-Data automatically parses it to extract connection parameters:

// These are equivalent:
form.submit('https://api.example.com:8443/upload/files');

form.submit({
  protocol: 'https:',
  host: 'api.example.com',
  port: 8443,
  path: '/upload/files',
  method: 'post'
});

Automatic Headers

The submit method automatically handles several headers:

  • Content-Type: Set to multipart/form-data; boundary=...
  • Content-Length: Calculated automatically when possible
  • User Headers: Merged with form headers using getHeaders()
const form = new FormData();
form.append('data', 'value');

// Custom headers are merged
form.submit({
  host: 'example.com',
  path: '/api',
  headers: {
    'User-Agent': 'MyApp/1.0',
    'X-Custom': 'value'
  }
}, callback);

Protocol Selection

Form-Data automatically selects the appropriate HTTP module:

  • HTTPS: Used when protocol: 'https:' or URL starts with https://
  • HTTP: Used for all other cases (default)
// Uses HTTPS module
form.submit('https://secure.example.com/upload', callback);
form.submit({ protocol: 'https:', host: 'secure.example.com' }, callback);

// Uses HTTP module  
form.submit('http://example.com/upload', callback);
form.submit({ host: 'example.com' }, callback); // defaults to HTTP

Error Handling

The submit method handles various error scenarios:

form.submit('http://example.com/upload', (err, res) => {
  if (err) {
    // Network errors, DNS resolution failures, etc.
    if (err.code === 'ENOTFOUND') {
      console.error('Host not found');
    } else if (err.code === 'ECONNREFUSED') {
      console.error('Connection refused');
    } else {
      console.error('Other error:', err.message);
    }
    return;
  }
  
  // HTTP errors (4xx, 5xx status codes)
  if (res.statusCode >= 400) {
    console.error('HTTP error:', res.statusCode, res.statusMessage);
  }
  
  res.resume();
});

Integration with HTTP Clients

For more advanced HTTP handling, you can integrate with other libraries:

// Using with 'request' library
const request = require('request');
const form = new FormData();
form.append('file', fs.createReadStream('file.txt'));

request.post({
  url: 'http://example.com/upload',
  formData: form
}, (err, res, body) => {
  console.log('Response:', body);
});

// Using with 'axios'
const axios = require('axios');
const form = new FormData();
form.append('data', 'value');

axios.post('http://example.com/api', form, {
  headers: form.getHeaders()
}).then(response => {
  console.log('Success:', response.data);
});

docs

browser-compatibility.md

buffer-operations.md

form-construction.md

headers-boundaries.md

http-submission.md

index.md

length-calculation.md

tile.json