Jérôme Decoster

Jérôme Decoster

3x AWS Certified - Architect, Developer, Cloud Practionner

12 Dec 2019

Node + Express + Sharp

The Goal
Create an API with express and sharp to convert an color image from to black and white version.

    Install and start the application

    Get the code from this github repository :

    # download an image hosted in a github repository
    $ git clone \
        --depth 1 \
        https://github.com/jeromedecoster/black-white-node-express-sharp.git \
    # cd + install
    $ cd /tmp/bw && npm install

    If you look at index.js, the code is really simple :

    const app = express()
    // memory storage
    var upload = multer({ storage: multer.memoryStorage() })
    app.post('/upload', upload.single('file'), (req, res) => {
        // convert
            .toBuffer(function (err, buffer) {
                // add a header to display the image rather than download it
                res.header('Content-Type', 'image/jpeg')

    Let’s start the server :

    # start the server
    $ node .

    Convert an image using a HTML form

    If you open localhost:3000 you should see :


    This is a multipart/form-data form grabbed from tympanus.

    Select the file /tmp/bw/bird.jpg and upload it :



    Now you should be redirected to /upload and see :


    Convert an image using curl

    We can use curl to upload then save the gray version :

    # upload `bird.jpg` and save the result as `bird-gray.jpg`
    $  curl --request POST \
        --form "file=@bird.jpg" \
        --silent \
        http://localhost:3000/upload \
        --output bird-gray.jpg