docs(clone): add promise example

This commit is contained in:
Vincent Voyer
2020-04-02 13:06:11 +02:00
committed by Lovell Fuller
parent 6ed1f49ad3
commit 1eedb22ef5
2 changed files with 97 additions and 0 deletions

View File

@@ -89,6 +89,55 @@ readableStream.pipe(pipeline);
// secondWritableStream receives auto-rotated, extracted region of readableStream
```
```javascript
// Create a pipeline that will download an image, resize it and format it to different files
// Using Promises to know when the pipeline is complete
const fs = require("fs");
const got = require("got");
const sharpStream = sharp({
failOnError: false
});
const promises = [];
promises.push(
sharpStream
.clone()
.jpeg({ quality: 100 })
.toFile("originalFile.jpg")
);
promises.push(
sharpStream
.clone()
.resize({ width: 500 })
.jpeg({ quality: 80 })
.toFile("optimized-500.jpg")
);
promises.push(
sharpStream
.clone()
.resize({ width: 500 })
.webp({ quality: 80 })
.toFile("optimized-500.webp")
);
// https://github.com/sindresorhus/got#gotstreamurl-options
got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream);
Promise.all(promises)
.then(res => { console.log("Done!", res); })
.catch(err => {
console.error("Error processing files, let's clean it up", err);
try {
fs.unlinkSync("originalFile.jpg");
fs.unlinkSync("optimized-500.jpg");
fs.unlinkSync("optimized-500.webp");
} catch (e) {}
});
```
Returns **[Sharp][8]**
[1]: https://nodejs.org/api/buffer.html