Skip to content
This repository has been archived by the owner on Nov 14, 2018. It is now read-only.

Commit

Permalink
Bitmap cache.
Browse files Browse the repository at this point in the history
Bitmap images (PNG & friends) are cached in memory.

Note: the cache is not discriminatory and grows constantly.

Part of issue #23.
  • Loading branch information
espadrine committed Jan 10, 2014
1 parent 96f2f96 commit 2877a78
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions svg-to-img.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ var phantom = require('phantomjs');
var childProcess = require('child_process');
var phantomScript = path.join(__dirname, 'phantomjs-svg2png.js');

var imgCache = Object.create(null);

// If available, use the font here.
var fontPath = './Verbana.ttf';
try {
Expand All @@ -13,17 +15,43 @@ try {
} catch(e) {}

module.exports = function (svg, format, out, cb) {
var cacheIndex = format + svg;
if (imgCache[cacheIndex] !== undefined) {
// We own a cache for this svg conversion.
imgCache[cacheIndex].pipe(out);
}
var tmpFile = path.join(os.tmpdir(),
"svg2img-" + (Math.random()*2147483648|0) + "." + format);
// Conversion to PNG happens in the phantom script.
childProcess.execFile(phantom.path, [phantomScript, svg, tmpFile],
function(err, stdout, stderr) {
if (stdout) { console.log(stdout); }
if (stderr) { console.log(stderr); }
if (stderr) { console.error(stderr); }
if (err != null) { console.error(err.stack); if (cb) { cb(err); } return; }
var inStream = fs.createReadStream(tmpFile);
inStream.pipe(out);
var cached = [];
inStream.on('data', function(chunk) {
cached.push(chunk);
out.write(chunk);
});
// Remove the temporary file after use.
inStream.on('end', function() { fs.unlink(tmpFile, cb); });
inStream.on('end', function() {
out.end();
imgCache[cacheIndex] = streamFromData(cached);
fs.unlink(tmpFile, cb);
});
});
};

// Fake stream from the cache.
var stream = require('stream');
function streamFromData(data) {
var newStream = new stream.Readable();
newStream._read = function() {
for (var i = 0; i < data.length; i++) {
newStream.push(data[i]);
}
newStream.push(null)
};
return newStream;
}

0 comments on commit 2877a78

Please sign in to comment.