{"id":17692,"library":"http-file","title":"HTTP Request/Response File Persistence","description":"`http-file` is a TypeScript library designed for serializing and deserializing complete HTTP request and response objects to and from a structured file format. It provides core classes like `RequestFile` and `ResponseFile` to encapsulate all relevant HTTP interaction data, including method, URL, headers, and body, along with utility functions such as `readRequestFile`, `writeRequestFile`, `readResponseFile`, and `writeResponseFile` for file system operations. This capability is particularly useful for scenarios requiring the persistence of HTTP traffic, such as creating mock servers from recorded interactions, replaying requests for testing or debugging, or sharing specific HTTP payloads. The package is currently at version 1.0.3. While it ships with full TypeScript types and offers a stable API, its last release was over two years ago, indicating a mature, low-cadence maintenance or stable phase rather than active feature development. Its key differentiator lies in its focused approach to structured file-based storage of entire HTTP dialogues, distinct from general-purpose HTTP clients or static file servers.","status":"active","version":"1.0.3","language":"javascript","source_language":"en","source_url":"https://github.com/mappies/http-file","tags":["javascript","typescript"],"install":[{"cmd":"npm install http-file","lang":"bash","label":"npm"},{"cmd":"yarn add http-file","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-file","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primarily designed for ESM and TypeScript; CommonJS requires dot-notation access to named exports.","wrong":"const RequestFile = require('http-file').RequestFile;","symbol":"RequestFile","correct":"import { RequestFile } from 'http-file';"},{"note":"All public functions and classes are named exports from the main package entry point.","wrong":"import readRequestFile from 'http-file/readRequestFile';","symbol":"readRequestFile","correct":"import { readRequestFile } from 'http-file';"},{"note":"Destructuring named imports is the recommended pattern for clarity and tree-shaking.","wrong":"import * as httpFile from 'http-file'; const myResponse = new httpFile.ResponseFile();","symbol":"ResponseFile","correct":"import { ResponseFile, writeResponseFile } from 'http-file';"}],"quickstart":{"code":"import { RequestFile, ResponseFile, writeRequestFile, readRequestFile, writeResponseFile, readResponseFile } from 'http-file';\nimport * as fs from 'fs/promises'; // For file cleanup\n\nasync function exampleUsage() {\n  const requestFilePath = 'example-request.http.json';\n  const responseFilePath = 'example-response.http.json';\n\n  // 1. Create a RequestFile instance\n  const requestData: RequestFile = {\n    method: 'GET',\n    url: 'https://api.example.com/data/items/1?cache=false',\n    headers: {\n      'Content-Type': 'application/json',\n      'Accept': 'application/json',\n      'Authorization': `Bearer ${process.env.API_KEY ?? 'YOUR_FALLBACK_TOKEN'}`, // Use env var for sensitive data\n    },\n    body: null,\n  };\n\n  // 2. Write the RequestFile to disk\n  await writeRequestFile(requestFilePath, requestData);\n  console.log(`Request file written to ${requestFilePath}`);\n\n  // 3. Read the RequestFile from disk\n  const loadedRequest = await readRequestFile(requestFilePath);\n  console.log('Loaded request URL:', loadedRequest.url);\n\n  // 4. Create a ResponseFile instance\n  const responseData: ResponseFile = {\n    statusCode: 200,\n    headers: {\n      'Content-Type': 'application/json',\n      'X-Request-ID': 'unique-abc-123',\n      'Cache-Control': 'no-cache'\n    },\n    body: JSON.stringify({ message: 'Data fetched successfully', data: { id: 1, name: 'Item 1' } }),\n  };\n\n  // 5. Write the ResponseFile to disk\n  await writeResponseFile(responseFilePath, responseData);\n  console.log(`Response file written to ${responseFilePath}`);\n\n  // 6. Read the ResponseFile from disk\n  const loadedResponse = await readResponseFile(responseFilePath);\n  console.log('Loaded response status:', loadedResponse.statusCode);\n  console.log('Loaded response body:', loadedResponse.body ? JSON.parse(loadedResponse.body.toString()) : null);\n\n  // Clean up created files\n  await fs.unlink(requestFilePath);\n  await fs.unlink(responseFilePath);\n  console.log('Cleaned up example files.');\n}\n\nexampleUsage().catch(console.error);","lang":"typescript","description":"This quickstart demonstrates how to create `RequestFile` and `ResponseFile` objects, write them to disk, and then read them back, showcasing the library's core serialization and deserialization capabilities."},"warnings":[{"fix":"Never commit files containing sensitive information to public repositories. Implement robust access controls for local storage and consider encrypting files if they contain highly sensitive data.","message":"Storing sensitive HTTP request or response data (e.g., authorization tokens, user credentials, private data in bodies) directly to files on disk can be a security risk. Ensure these files are stored in secure locations with appropriate access controls and are not committed to version control systems.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always validate file paths and ensure necessary directory structures exist and have correct permissions before attempting write operations. Wrap file operations in `try-catch` blocks to handle potential `fs` errors gracefully.","message":"The library primarily operates on file paths. Incorrect or invalid file paths (e.g., non-existent directories, permission issues) will result in standard Node.js file system errors (e.g., `ENOENT`, `EACCES`) rather than custom library errors. These errors will be thrown by the underlying `fs/promises` module.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For binary HTTP bodies (e.g., images, downloads), ensure you convert the data to a Node.js `Buffer` before assigning it to the `body` property. When reading, check `Buffer.isBuffer(loadedObject.body)` and handle accordingly.","message":"The `body` property for `RequestFile` and `ResponseFile` supports `string | null | Buffer`. When dealing with non-UTF-8 textual content or binary data, it is crucial to pass a `Buffer` instance to preserve data integrity. Storing binary data as a plain string might lead to corruption or incorrect interpretation.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure the directory exists before writing, and the file exists before reading. Use `fs.mkdir(path, { recursive: true })` for directories.","cause":"The specified file path for reading or writing does not exist or refers to an invalid location.","error":"Error: ENOENT: no such file or directory, open 'path/to/non-existent-file.json'"},{"fix":"Always pass a valid string representing the file path to the library's file I/O functions.","cause":"A non-string value (e.g., `null`, `undefined`, an object) was passed as the file path argument to `readRequestFile`, `writeRequestFile`, or related functions.","error":"TypeError: The \"path\" argument must be of type string. Received type object"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}