1.0.0 • Published 6 months ago

als-stream-copy v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

als-stream-copy

als-stream-copy is a simple, promise-based Node.js module for copying files using streams. It ensures that if an error occurs during copying, the partially created destination file is removed and an error is thrown with details about both the primary issue and any secondary cleanup error.

Features

  1. Stream-based copying: Optimized for large files, as it does not load the entire file into memory.
  2. Automatic directory creation: Ensures the destination directory structure exists before copying.
  3. Automatic cleanup: If any error occurs, the partially copied destination file is removed to avoid corrupt files.
  4. Detailed error reporting: In case the removal of the destination file fails, the module attaches the secondary cleanup error to the main error object.

Installation

Install via npm:

npm install als-stream-copy

Usage

const copyFile = require('als-stream-copy');

(async () => {
  try {
    await copyFile('source.txt', 'destination.txt');
    console.log('File copied successfully!');
  } catch (err) {
    console.error('Error during file copy:', err);
  }
})();
  • copyFile(src, dest) returns a Promise:
    • resolves when copying finishes successfully,
    • rejects if an error occurs.

Error Handling

Primary Error

If copying fails for any reason (e.g., the source file is missing, the read/write stream encounters an I/O error), copyFile rejects with a primary error object. For example, if source.txt does not exist, you might see:

try {
  await copyFile('nonexistent.txt', 'destination.txt');
} catch (err) {
  console.error(err); 
  // "nonexistent.txt not exists"
}

Secondary Cleanup Error

When an error occurs during copying, als-stream-copy attempts to remove the partially copied dest file to prevent corruption. If that removal process also fails, the module attaches the secondary error to the primary error object under the error property.

For instance:

try {
  await copyFile('source.txt', '/restricted/destination.txt');
} catch (err) {
  console.error(err);
  /*
    The primary error could be a permission error: EACCES
    If removing the file also fails, the second error will be in err.error
  */
}

This approach provides more visibility into what went wrong both during the copying process and any subsequent cleanup attempt.


Differences from Regular Copy Functions

fs.copyFile (Node.js native)

  • Does not remove the destination file if an error occurs mid-copy.
  • No automatic directory creation.
  • Does not store secondary errors if cleanup fails.

als-stream-copy

  • Uses read/write streams for potentially memory-efficient copying of large files.
  • Automatically creates missing directories.
  • Removes the destination file if the copy fails.
  • Appends cleanup failure details (secondary error) to the original error.