diff --git a/index.js b/index.js index 21fdacf..6bcb95d 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ const fs = require('fs-extra'); const path = require('path'); const pcbStackup = require('pcb-stackup'); const sharp = require('sharp'); +const { Readable } = require('stream'); // Filenames we need to extract from the archive const gerberFiles = [ @@ -146,6 +147,54 @@ class ImageGenerator { }); }); } + + /** + * Take an archive containing gerber files and return a stream containing + * a PNG image from the gerber + * @param {string} gerber Path to an archive file containing gerber + * @returns {Promise.} Promise that resolves to a PNG stream + */ + gerberToStream(gerber) { + // Check temp and output dirs exist + try { + if (!fs.existsSync(gerber)) { + throw Error('Archive does not exist.'); + } + if (!fs.existsSync(this.tmpDir)) { + throw Error('Temporary folder does not exist.'); + } + if (!fs.existsSync(this.imgDir)) { + throw Error('Output folder does not exist.'); + } + } catch (e) { + throw new Error(e); + } + + return new Promise((resolve, reject) => { + ImageGenerator.extractArchive(gerber, this.tmpDir); + ImageGenerator.getLayers(path.join(this.tmpDir, 'archive')) + .then(pcbStackup) + .then((stackup) => { + sharp(Buffer.from(stackup.top.svg), { + density: this.imgConfig.density, + }) + .resize({ width: this.imgConfig.resizeWidth }) + .png({ compressionLevel: this.imgConfig.compLevel }) + .toBuffer() + .then((buffer) => { + ImageGenerator.cleanupFiles(this.tmpDir); + const stream = new Readable(); + stream.push(buffer); + stream.push(null); + resolve(stream); + }); + }) + .catch((e) => { + ImageGenerator.cleanupFiles(this.tmpDir); + reject(new Error(e)); + }); + }); + } } module.exports = { diff --git a/test/index.test.js b/test/index.test.js index ae7fa60..138b0dd 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -1,6 +1,7 @@ /* eslint-disable */ const path = require('path'); const fs = require('fs-extra'); +const Readable = require('stream').Readable; const { ImageGenerator } = require('../index.js'); require('../index.js'); @@ -110,3 +111,11 @@ test('Gerber archive should resolve promise and return a filename of an image', fileProc.gerberToImage(testGerber) ).resolves.toEqual(expect.stringContaining('Arduino-Pro-Mini.png')); }); + +// gerberToStream +test('Gerber archive should resolve promise and return a png stream', () => { + expect.assertions(1); + return expect( + fileProc.gerberToStream(testGerber) + ).resolves.toBeInstanceOf(Readable); +});