Skip to content

Instantly share code, notes, and snippets.

@joshwcomeau
Last active May 12, 2016 13:24
Show Gist options
  • Save joshwcomeau/bab5fef0d1b6ce7694a0abd52d7075b0 to your computer and use it in GitHub Desktop.
Save joshwcomeau/bab5fef0d1b6ce7694a0abd52d7075b0 to your computer and use it in GitHub Desktop.
convert-to-async
app.post('/process-upload', upload.single('image'), async (req, res) => {
// These helper methods aren't as necessary anymore, but they still
// provide semantic value that makes the route easier to follow.
const resizeAndConvert = buffer => (
imConvertPromise({
srcData: buffer,
width: 32,
height: 16,
format: 'PNG'
})
);
const readPixelsFromImage = buffer => (
imageMagick.getConstPixels({
srcData: buffer,
x: 0,
y: 0,
columns: 32,
rows: 16
})
);
// Our saveToDisk method is now much more intuitive; no hidden complexity!
const saveToDisk = (file, buffer) => (
writeFilePromise(getPathForNewFile(file), buffer)
);
// Because this is native javascript, native constructs like try/catch,
// `if` statements, and loops can be used!
try {
// The `await` keyword instructs the engine to wait, in a non-blocking
// way, for the function to return before continuing.
const originalFileBuffer = await readFilePromise(req.file.path);
const smallFileBuffer = await resizeAndConvert(originalFileBuffer);
await saveToDisk(req.file, smallFileBuffer);
const pixels = readPixelsFromImage(smallFileBuffer);
return res.json({ done: true, pixels });
} catch (err) {
throw err;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment