/** * Save buffer data to a file. * @param {Buffer} buffer - buffer to save to a file. * @param {string} filePath - path to a file. */ const saveBufferToFile = (buffer, filePath, callback) => { if (!Buffer.isBuffer(buffer)) { return callback(new Error('buffer variable should be type of Buffer!')); } // Setup readable stream from buffer. let streamData = buffer; let readStream = Readable(); readStream._read = () => { readStream.push(streamData); streamData = null; }; // Setup file system writable stream. let fstream = fs.createWriteStream(filePath); fstream.on('error', err => callback(err)); fstream.on('close', () => callback()); // Copy file via piping streams. readStream.pipe(fstream); }