Friday, November 10, 2023

Node JS read and write to a location

 const sourcePath = 'path/to/source/binaryfile.bin';

const destinationPath = 'path/to/destination/binaryfile.bin';


// Create a readable stream from the source file

const readStream = fs.createReadStream(sourcePath, { highWaterMark: 64 * 1024 }); // You can adjust the highWaterMark value for performance optimization


// Create a writable stream to the destination file

const writeStream = fs.createWriteStream(destinationPath);


// Pipe the contents from the source to the destination

readStream.pipe(writeStream);


// Handle events for completion and errors

readStream.on('end', () => {

  console.log(`File moved from ${sourcePath} to ${destinationPath}`);

  // Optional: Delete the source file

  fs.unlink(sourcePath, (unlinkErr) => {

    if (unlinkErr) {

      console.error(`Error deleting source file: ${unlinkErr}`);

    } else {

      console.log(`Source file ${sourcePath} deleted`);

    }

  });

});


readStream.on('error', (error) => {

  console.error(`Error reading source file: ${error}`);

});


writeStream.on('error', (error) => {

  console.error(`Error writing to destination file: ${error}`);

});


No comments:

Post a Comment