Read Image From mongoDB Using Node.js

By Yashwant Chavan, Views 13816, Last updated on 03-Mar-2019

In this tutorial, You will learn how to Read / Download image from MongoDB database using node.js, This step by step guide will help you to install MongoDB module, setup nodejs project and sample code to read file from mongodb database using GridFS API.

tags nodejs

Tools and Technologies

  • Node Version 6.9.4
  • Mongodb 3.3.12
  • Eclipse Mars

Nodejs Project Structure using Eclipse

Read image from mongodb using nodejs - Eclipse Project Structure

Install nodejs mongodb module

package.json file contains the metadata information, Which helps to maintain node module dependencies. Add mongodb dependency in package.json or You can install mongodb module manually using npm install mongodb command.

"dependencies": {
    "mongodb": "*"
}

package.json

{
    "name": "NodejsExamples",
    "version": "0.1.0",
    "description": "NodejsExamples",
    "main": "node-mongodb-example.js",
    "scripts": {
        "test": "echo \"Error: no test specified! Configure in package.json\" && exit 1"
    },
    "repository": "",
    "dependencies": {
        "mongodb": "*"
    },
    "keywords": [
    "node.js",
    "eclipse",
    "nodeclipse"
  ],
    "author": "",
    "license": "MIT",
    "readmeFilename": "README.md"
}

Right click on package.json then select Run As -> npm install option. It will start downloading mongodb and dependent npm dependencies. Refer below log details.

Install nodejs mongodb module

mongodb npm installation log

Once installation is done, You will find mongodb module in "node_modules" folder.

NodejsExamples@0.1.0 C:\javaworkspace\NodejsExamples
`-- mongodb@2.2.22 
  +-- es6-promise@3.2.1 
  +-- mongodb-core@2.1.7 
  | +-- bson@1.0.4 
  | `-- require_optional@1.0.0 
  |   +-- resolve-from@2.0.0 
  |   `-- semver@5.3.0 
  `-- readable-stream@2.1.5 
    +-- buffer-shims@1.0.0 
    +-- core-util-is@1.0.2 
    +-- inherits@2.0.3 
    +-- isarray@1.0.0 
    +-- process-nextick-args@1.0.7 
    +-- string_decoder@0.10.31 
    `-- util-deprecate@1.0.2 

npm WARN NodejsExamples@0.1.0 No repository field.

Mongodb collection ("images")

In the previous article, I discussed how to store image into mongodb using nodejs. Here, We will learn how to DOWNLOAD image from mongodb using nodejs. Refer below "images" GridFS collections.

> use technicalkeeda
switched to db technicalkeeda
> show collections
images.chunks
images.files
persons
system.indexes
system.profile
> db.images.files.find()
{ "_id" : ObjectId("5897fe852a14f91d48a66cbd"), "length" : 13291, "chunkSize" : 1024, "uploadDate" : ISODate("
2017-02-06T04:41:42.210Z"), "md5" : "c6f06b0bdc11b04d334c8cd85771d332", "filename" : "dog.jpg" }
>

Download image from mongodb using nodejs

require('mongodb') - Load the mongodb module to connect to mongob database.

require('fs') - Load the fs module to read image file from local drive.

require('mongodb').MongoClient - Create a new MongoClient instance.

mongoClient.connect() method is used to connect to MongoDB database using connection url.

new mongodb.GridFSBucket() - To use GridFS streaming API, You need to create a GridFSBucket instance. You can specify "chunkSizeBytes" and "bucketName", otherwise it will take default options.

In this example, We are going to read image file ("dog.jpg") from mongodb database and write it to physical path c:\\demo\\dog.jpg.

The bucket has an openDownloadStreamByName() method which opens a readable stream. Once stream is available, use fs.createWriteStream() function to write the stream data.

var mongodb = require('mongodb');
var mongoClient = mongodb.MongoClient;
var fs = require('fs');

var url = 'mongodb://localhost:27017/technicalkeeda';

mongoClient.connect(url, function(err, db) {

    if (err) {
        console.log('Sorry unable to connect to MongoDB Error:', err);
    } else {

        var bucket = new mongodb.GridFSBucket(db, {
            chunkSizeBytes: 1024,
            bucketName: 'images'
        });

        bucket.openDownloadStreamByName('dog.jpg').pipe(
            fs.createWriteStream('c:\\demo\\dog.jpg')).on('error',
            function(error) {
                console.log('Error:-', error);
            }).on('finish', function() {
            console.log('done!');
            process.exit(0);
        });
    }
});

Run & Execute

Right click on node-mongodb-example.js file, select Run As -> Node Application option to execute the nodejs program.

Execute - Read image from mongodb using nodejs

output

done!
1 Comments
Avatar

Dilip Singh

Out standing and very easy tutorial. Yashwant!! Please keep it up the good work. Its simple and step by step guide. If possible please post interview questions post on node.js ?

Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]