Search code examples
node.jsencryptioncryptojs

How do you encrypt only a part of a whole file (example: first 2500 bytes only) in nodejs?


I'm working on a node app that encrypts and decrypts files using crypto. But right now I'm trying to encrypt only a specific n size of a file. For example, I only want to encrypt the first 2500 bytes of a file, then write the buffer again to the disk (The first 2500 bytes are encrypted and the rest is as is)

Any thoughts?


Solution

  • I'm not sure how you're encrypting the data, but it's not important here.

    The key idea is to just read the first 2500 bytes of the file, and then write those bytes back (encrypted) using the r+ flag for fs.createWriteStream. Specifically, fs.createWriteStream(file, {start: 0, flags: 'r+'}) will start writing at the beginning of the file. Simply write the 2500 encrypted bytes to the file stream and you're done.