<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Node JS &#8211; Sibeesh Passion</title>
	<atom:link href="https://sibeeshpassion.com/category/node-js/feed/" rel="self" type="application/rss+xml" />
	<link>https://sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 11 Jul 2018 16:21:43 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Node JS &#8211; Sibeesh Passion</title>
	<link>https://sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io</title>
		<link>https://sibeeshpassion.com/creating-a-chat-application-in-node-js-with-express-mongodb-mongoose-and-socket-io/</link>
					<comments>https://sibeeshpassion.com/creating-a-chat-application-in-node-js-with-express-mongodb-mongoose-and-socket-io/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 04 Dec 2017 12:09:50 +0000</pubDate>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node JS]]></category>
		<category><![CDATA[Chat Application in Node JS]]></category>
		<category><![CDATA[Chat Application using Socket.io]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[Simple client side chat application]]></category>
		<category><![CDATA[Socket.io]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12595</guid>

					<description><![CDATA[[toc] Introduction In this article, we are going to a chat application in Node JS  with the back end MongoDB.  We will also be using Mongoose for creating the MongoDB models and Socket.io for making multi directional chats on multiple client window. If you are really new to the Node JS, I strongly recommend you to read some articles on the same here. You can also see how you can create a sample Node application with MongoDB and Mongoose here. At the end of this article, I guarantee that you will be having some basic knowledge on the mentioned technologies. I hope you will [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>In this article, we are going to a chat application in <a href="http://sibeeshpassion.com/category/Node-JS/">Node JS</a>  with the back end <a href="http://sibeeshpassion.com/category/MongoDB">MongoDB.</a>  We will also be using <a href="http://sibeeshpassion.com/tag/Mongoose/">Mongoose</a> for creating the MongoDB models and <a href="http://sibeeshpassion.com/tag/Socket.io/">Socket.io</a> for making multi directional chats on multiple client window. If you are really new to the Node JS, I strongly recommend you to read some articles on the same <a href="http://sibeeshpassion.com/category/Node-JS/">here</a>. You can also see how you can create a sample Node application with MongoDB and Mongoose <a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">here</a>. At the end of this article, I guarantee that you will be having some basic knowledge on the mentioned technologies. I hope you will like this article.</p>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://code.msdn.microsoft.com/ChatApp-NodeJS-Socketio-22325371">here</a></p>
<h3>Background</h3>
<p>Creating a chat application is always an interesting this to do. And it is a good way to learn a lot, because you are creating some interactions on your application. And with the release of few technologies we can create such application without any hassle. It is much more easier than ever. Here we are also going to create a chat application. A basic knowledge of Node JS, MongoDB, JavaScript, JQuery is more than enough to create this project. So, please be with me. Let&#8217;s just skip the talking and start developing.</p>
<h3>Setting up Node application</h3>
<p>This step requires some basic knowledge, please see some of that <a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">here</a>.  So as mentioned in that article, we have successfully created our Package.json file and installed the required packages. Let&#8217;s review our package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
 "name": "chatapp",
 "version": "1.0.0",
 "description": "A chat application in Node JS, which uses MongoDB, Mongoose and Socket.io",
 "main": "index.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
 },
 "keywords": [
 "Node",
 "JS",
 "MongoDB",
 "Mongoose",
 "Socket.io"
 ],
 "author": "Sibeesh Venu",
 "license": "ISC",
 "dependencies": {
 }
}
</pre>
<p>Let&#8217;s install the packages now by running the below commands.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save express
npm install --save mongoose
npm install --save body-parser
npm install --save socket.io</pre>
<p>Now that we have all the dependencies added to the package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">"dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2",
    "mongoose": "^4.13.6",
    "socket.io": "^2.0.4"
  }</pre>
<h4>Creating an App using Express</h4>
<p>Let&#8217;s create a file server.js and build an app using Express.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var express = require("express")
var app = express()
app.listen(3020,()=&gt;{
 console.log("Well done, now I am listening...")
})</pre>
<p>I hope you are getting  the desired output, if not, please don&#8217;t worry, just double check the codes you had written.</p>
<h4>Running our application on browser</h4>
<p>Let&#8217;s run our application on port 3020 and see what we are getting <a href="http://localhost:3020/">http://localhost:3020/</a>..</p>
<p>Yes you will get an error as <code class="EnlighterJSRAW" data-enlighter-language="js">Cannot GET /</code>  , no worries. To fix that you need to add the following code block to your server.js file</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.use(express.static(__dirname))</pre>
<h4>Creating Index page</h4>
<p>Here I am going to create a <a href="http://sibeeshpassion.com/category/HTML5/">HTML 5</a> page with <a href="http://sibeeshpassion.com/category/JQuery/">JQuery</a> and Bootstrap referenced in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="html">&lt;!DOCTYPE html&gt;
&lt;title&gt;Creating a Chat Application in Node JS with Express, MongoDB, Mongoose and Socket.io&lt;/title&gt;
&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" crossorigin="anonymous"&gt;
&lt;script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" crossorigin="anonymous"&gt;&lt;/script&gt;
&lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" crossorigin="anonymous"&gt;&lt;/script&gt;

&lt;div class="container"&gt;
    &lt;br&gt;
    &lt;div class="jumbotron"&gt;
        &lt;h1 class="dispaly-4"&gt;Start Chatting&lt;/h1&gt;
        &lt;br&gt;
        &lt;input id="txtName" class="form-control" placeholder="Name" type="text"&gt;
        &lt;br&gt;
        &lt;textarea id="txtMessage" class="form-control" placeholder="Message"&gt;&lt;/textarea&gt;
        &lt;br&gt;
        &lt;button id="send" class="btn btn-success"&gt;Send&lt;/button&gt;
    &lt;/div&gt;
    &lt;div id="messages"&gt;&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>As you can see, the page has two text boxes and one button. We will be creating some scripts very soon which uses these controls.</p>
<h3>Start developing the chat app</h3>
<p>Till now, it was all basic, and we have done it well. Now it is time to go and write some advanced codes. So, are you ready?</p>
<h4>Create model from page data</h4>
<p>Here we are going to create the model from the page data, that is, from the controls we have in our page. We will be using JQuery to do so.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">&lt;script&gt;
    $(() =&gt; {
        $("send").click(() =&gt; {
            var chatMessage = {
                name: $("#txtName").val(), chat: $("#txtMessage").val()
            }
            postChat(chat)
        })
    })

    function postChat(chat){
        console.log(chat)
    }

&lt;/script&gt;</pre>
<p>Now that we have got the model from the user, let&#8217;s save it to the DB.</p>
<div id="attachment_12596" style="width: 428px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Model-values-on-browser-console.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-12596" class="size-full wp-image-12596" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Model-values-on-browser-console.png" alt="Model values on browser console" width="418" height="446" srcset="/wp-content/uploads/2017/12/Model-values-on-browser-console.png 418w, /wp-content/uploads/2017/12/Model-values-on-browser-console-281x300.png 281w, /wp-content/uploads/2017/12/Model-values-on-browser-console-400x427.png 400w" sizes="(max-width: 418px) 100vw, 418px" /></a><p id="caption-attachment-12596" class="wp-caption-text">Model values on browser console</p></div>
<h4>Setting up database</h4>
<p>We are going to set up our database in mLab as mentioned in this article <a href="http://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/">Using MongoDB on Node JS Application Using Mongoose.</a> So let&#8217;s just require Mongoose and do the needed changes.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var express = require("express")
var mongoose = require("mongoose")

var app = express()

var conString = "mongodb://admin:admin@ds038319.mlab.com:38319/mylearning"
app.use(express.static(__dirname))

var Chats = mongoose.model("Chats", {
    name: String,
    chat: String
})

mongoose.connect(conString, { useMongoClient: true }, (err) =&gt; {
    console.log("Database connection", err)
})

app.listen(3020, () =&gt; {
    console.log("Well done, now I am listening...")
})</pre>
<h4>Creating a Post request</h4>
<p>Now let&#8217;s create a post requests in our index.html file which will the post API in our server.js file.</p>
<p><em><span style="text-decoration: underline;">index.html</span></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">function postChat(chat) {
        $.post("http://localhost:3020/chats", chat)
}</pre>
<p><span style="text-decoration: underline;"><em>server.js</em></span></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.post("/chats", async (req, res) =&gt; {
    try {
        var chat = new Chats(req.body)
        await chat.save()
        res.sendStatus(200)
    } catch (error) {
        res.sendStatus(500)
        console.error(error)
    }
})
</pre>
<p>Let&#8217;s just run our application and test it out.</p>
<p>You may be getting an error as &#8220;(node:10824) DeprecationWarning: Mongoose: mpromise (mongoose&#8217;s default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html&#8221;&#8221;, here to fix this, we need to use the default promise instead of the Mongoose promise. Let&#8217;s change that. Add this code <code class="EnlighterJSRAW" data-enlighter-language="js">mongoose.Promise = Promise</code> to our server.js file. Give it a try after setting it.</p>
<p>Still it is not working right, you are getting <em>undefined </em>at the place, <code class="EnlighterJSRAW" data-enlighter-language="js">var chat = new Chats(req.body)</code> in our Post API . At this stage, we will have to use our body-parser packages, do you remember the package we have installed? Let&#8217;s just require that package <code class="EnlighterJSRAW" data-enlighter-language="js">var bodyParser = require("body-parser")</code> add the preceding codes to our server.js file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))</pre>
<p>Now this will convert the request to a JSON object by default. Give it a try again, I am sure you will get the actual value instead of undefined.</p>
<h4>Creating a Get request for all the chat data</h4>
<p>We have written codes to write our data into our database, we will have to show this data on our page right? Here we are going to write the get requests in out index.html page which will call the get API.</p>
<p><em><span style="text-decoration: underline;">index.html</span></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="null">function getChats() {
     $.get("/chats", (chats) =&gt; {
         chats.forEach(addChat)
     })
}

function addChat(chatObj){
    $("#messages").append(`&lt;h5&gt;${chatObj.name} &lt;/h5&gt;&lt;p&gt;${chatObj.chat}&lt;/p&gt;`);
}</pre>
<p>And call the function getChats() in document ready event.</p>
<p><em><span style="text-decoration: underline;">server.js</span></em></p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.get("/chats", (req, res) =&gt; {
    Chats.find({}, (error, chats) =&gt; {
        res.send(chats)
    })
})</pre>
<p>Here we are passing {} to our find function, this means, we are going to get all the chats without any filter. Just run your application now, and check whether you are getting the chat messages you had sent.</p>
<div id="attachment_12597" style="width: 369px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB.png"><img decoding="async" aria-describedby="caption-attachment-12597" class="size-full wp-image-12597" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB.png" alt="Retrieving data from a MongoDB" width="359" height="514" srcset="/wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB.png 359w, /wp-content/uploads/2017/12/Retreiving-data-from-a-MongoDB-210x300.png 210w" sizes="(max-width: 359px) 100vw, 359px" /></a><p id="caption-attachment-12597" class="wp-caption-text">Retrieving data from a MongoDB</p></div>
<h3>Implementing Socket.io</h3>
<p>Now the chat we are sending is getting saved to our database and we are able to load the same on page load. Is it the behavior of a perfect chat application? Absolutely no, a perfect chat application will be able to,</p>
<ol>
<li>Show the chat message to the UI right after the data gets inserted to database</li>
<li>Show the chats in multiple clients, here in our application, if you are opening the URL in multiple browser instance, and if you need to show the chats to both instances, you will have to refresh the pages right? This is not a recommended way</li>
</ol>
<p>That&#8217;s why we are going to implement Socket.io in our application.</p>
<h4>Require the package</h4>
<p>Unlike the other packages, adding socket.io to the application is a different process, we will have to require the http server first, then, set our app. You can see more information on socket.io <a href="https://socket.io/">here</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var http = require("http").Server(app)
var io= require("socket.io")(http)</pre>
<h4>Enabling the connection</h4>
<p>To enable the connection, we need to use the function io.on.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">io.on("connection", (socket) =&gt; {
    console.log("Socket is connected...")
})</pre>
<h4>Listen using new http server</h4>
<p>Now that we have a new http server, and we should change our listen code to our new http.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var server = http.listen(3020, () =&gt; {
    console.log("Well done, now I am listening on ", server.address().port)
})</pre>
<h4>Changes in script</h4>
<p>Let&#8217;s do listen for the event &#8220;chat&#8221; now in our html page.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var socket = io()
socket.on("chat", addChat)</pre>
<p>Please do not forget to include the socket.io.js reference in our index page, other wise you may get an error as &#8220;Uncaught ReferenceError: io is not defined&#8221;</p>
<h4>Emits the event</h4>
<p>Once the above step is completed we need to make sure we are emitting the new event on our Post API.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">app.post("/chats", async (req, res) =&gt; {
 try {
 var chat = new Chats(req.body)
 await chat.save()
 res.sendStatus(200)

 //Emit the event
 io.emit("chat", req.body)

 } catch (error) {
 res.sendStatus(500)
 console.error(error)
 }
})</pre>
<p>&nbsp;</p>
<p>Let&#8217;s just run our application in two browser instances and check for the output.</p>
<div id="attachment_12598" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/Socket.io-Output-e1512388473997.png"><img decoding="async" aria-describedby="caption-attachment-12598" class="size-full wp-image-12598" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/Socket.io-Output-e1512388473997.png" alt="Socket.io Output" width="634" height="596" /></a><p id="caption-attachment-12598" class="wp-caption-text">Socket.io Output</p></div>
<p>Please make sure that you are getting the chats in the second instance when you send it from the first instance of the browser and vice versa.</p>
<p>&nbsp;</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/creating-a-chat-application-in-node-js-with-express-mongodb-mongoose-and-socket-io/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using MongoDB on Node JS Application Using Mongoose</title>
		<link>https://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/</link>
					<comments>https://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 03 Dec 2017 17:15:12 +0000</pubDate>
				<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Node JS]]></category>
		<category><![CDATA[Easy way to insert data to MongoDB]]></category>
		<category><![CDATA[MongoDB with Mongoose]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[Node JS and MongoDB]]></category>
		<category><![CDATA[NPM]]></category>
		<guid isPermaLink="false">https://sibeeshpassion.com/?p=12589</guid>

					<description><![CDATA[[toc] Introduction In this post, we are going to see how we can use a MongoDB on our Node JS application with the help of the package Mongoose. We will also be covering some facts about MongoDB so that as a reader, you will understand why we had chosen MongoDB as our backend. We will be going through some steps to install the required packages using a node package manager terminal, so please be with me. At the end of this article, I guarantee that you will be proficient on how to connect a MongoDB in our Node JS application. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>In this post, we are going to see how we can use a <a href="http://sibeeshpassion.com/category/MongoDB">MongoDB</a> on our Node JS application with the help of the package Mongoose. We will also be covering some facts about MongoDB so that as a reader, you will understand why we had chosen MongoDB as our backend. We will be going through some steps to install the required packages using a node package manager terminal, so please be with me. At the end of this article, I guarantee that you will be proficient on how to connect a MongoDB in our Node JS application. I hope you will like this article.</p>
<h3>Why MongoDB?</h3>
<p>Here, I am going to list down the reasons why I had chosen MongoDB.</p>
<ol>
<li>MongoDB is a NoSQL database when I say NoSQL, it means that it doesn&#8217;t have any structure to be followed.</li>
<li>There are no relationships, we can perform the relation using separate packages like Mongoose</li>
<li>Everything is JSON, even the data and collections are stored as JSON</li>
<li>Since the data is stored as JSON, no more conversions are needed. We can directly use it in our application.</li>
</ol>
<h3><span id="source-code">Source Code</span></h3>
<p>You can always clone or download the source code <a href="https://code.msdn.microsoft.com/Node-MongoDB-Mongoose-40fc3ad4">here</a></p>
<h3>Background</h3>
<p>Node JS has become a trend now, thus some most used databases. One of the recommended database for a Node application is MongoDB. As we discussed a MongoDB doesn&#8217;t have any structure inbuilt, here we are going to use a package called Mongoose, with that we can create some structure for our Database. Let&#8217;s just skip the talking and start developing.</p>
<h3>Setting up Node application</h3>
<p>To get started with the Node JS, create a folder and name as per your wish, this is going to be our project directory. Here I am going to use one of my favorite editor, Visual Studio Code. Now please point to your project container, and run the command below.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm init</pre>
<div id="attachment_12591" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/NPM-Init.png"><img decoding="async" aria-describedby="caption-attachment-12591" class="size-full wp-image-12591" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/NPM-Init.png" alt="NPM Init" width="634" height="449" srcset="/wp-content/uploads/2017/12/NPM-Init.png 504w, /wp-content/uploads/2017/12/NPM-Init-300x212.png 300w, /wp-content/uploads/2017/12/NPM-Init-400x283.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12591" class="wp-caption-text">NPM Init</p></div>
<p>This will create a file named &#8220;Package.json&#8221; in your directory. We will be adding all of our dependencies in this file very soon. The command may ask you some default questions which you need to answer. If you need to create the package.json file with default values in it, you may consider running the below command.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm init --yes</pre>
<p>Let&#8217;s review our package.json file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="json">{
  "name": "node-mongodb-mongoose",
  "version": "1.0.0",
  "description": "A Node application with MongoDB and Mongoose",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "keywords": [
    "Node",
    "Mongoose",
    "MongoDB"
  ],
  "author": "Sibeesh Venu",
  "license": "ISC"
}
</pre>
<h3>Getting the required packages</h3>
<p>Now that we have the application ready, let&#8217;s get the required packages ready.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save mongoose</pre>
<p>This will create a new folder npm_modules on your project directory where you can see the package Mongoose in it.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">npm install --save express</pre>
<p>The above command will add the package express to our application.</p>
<h3>Creating the Node App</h3>
<p>Now we can create our server.js file where we are going to write most of our application code.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var express = require("express")
var app = express()
app.listen("3010",()=&gt;{
    console.log("I just started listening!.")
})
</pre>
<p>Now run the command <code class="EnlighterJSRAW" data-enlighter-language="shell">node server.js</code>and make sure that you are getting a console as &#8221; I just started listening!.&#8221;.</p>
<p>If you are getting an error as preceding, please make sure that you are running the application on an unused port.</p>
<blockquote><p>PS F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose&gt; node server.js<br />
events.js:136<br />
throw er; // Unhandled &#8216;error&#8217; event<br />
^</p>
<p>Error: listen EADDRINUSE :::3000<br />
at Object._errnoException (util.js:1031:13)<br />
at _exceptionWithHostPort (util.js:1052:20)<br />
at Server.setupListenHandle [as _listen2] (net.js:1367:14)<br />
at listenInCluster (net.js:1408:12)<br />
at Server.listen (net.js:1496:7)<br />
at Function.listen (F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose\node_modules\express\lib\application.js:618:24)<br />
at Object.&lt;anonymous&gt; (F:\Visual Studio\Node.JS\Node-MongoDB-Mongoose\server.js:3:5)<br />
at Module._compile (module.js:641:30)<br />
at Object.Module._extensions..js (module.js:652:10)<br />
at Module.load (module.js:560:32)&#8221;</p></blockquote>
<h3>Setting up database</h3>
<p>Now that we have our application ready, let&#8217;s go and create our database. I am going to use mLab for creating the database. If you have not installed MongoDB on your machine, I strongly recommend creating a database in <a href="https://mlab.com/home">mLab.</a> I had created a database there and have got my connection string as preceding.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">mongodb://&lt;dbuser&gt;:&lt;dbpassword&gt;@ds038319.mlab.com:38319/mylearning</pre>
<p>We will be updating the connection string with actual DB user and password later. Please make sure that you are creating a user for your DB and remember the password.</p>
<h3>Creating a Mongoose model</h3>
<p>Let&#8217;s create a Mongoose model and set up our connection string now, which is going to be our collection. No worries, it is just a <a href="http://sibeeshpassion.com/category/JavaScript">JavaScript</a> model.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="shell">var conString = "mongodb://admin:admin@ds038319.mlab.com:38319/mylearning"

/**
 * Models 
 */
var User = mongoose.model("User", {
    firstName: String,
    lastName: String
})</pre>
<blockquote><p>Please be noted that, when you move the codes to production, make sure that your password and user fields on the connection string are separated from this file and encrypted</p></blockquote>
<p>Now let&#8217;s connect our database.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">mongoose.connect(conString, { useMongoClient: true }, () =&gt; {
    console.log("DB is connected")
})</pre>
<h3>Setup the data</h3>
<p>We have our model ready, what else is needed now? Yes, you are right, we need data.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">var dummyUser = {
    firstName: "Sibeesh",
    lastName: "Venu"
}</pre>
<h3>Inserting the data into MongoDB</h3>
<p>We have got everything ready, we can insert the model now. Let&#8217;s do the saving logic now.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="js">mongoose.connect(conString, { useMongoClient: true }, () =&gt; {
    console.log("DB is connected")
    saveData()
})</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="js">function saveData() {
    var user = new User(dummyUser);
    user.save();
}</pre>
<h3>Verify the data</h3>
<p>Once you run your application, go to your database and check for the entries there. I am sure there will be a new collection &#8220;User&#8221; and our inserted data. As I am using mLab database, here is how my data saved.</p>
<div id="attachment_12590" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2017/12/MongoDB-Data-Insertion.png"><img decoding="async" aria-describedby="caption-attachment-12590" class="size-full wp-image-12590" src="http://sibeeshpassion.com/wp-content/uploads/2017/12/MongoDB-Data-Insertion.png" alt="MongoDB Data Insertion" width="634" height="420" srcset="/wp-content/uploads/2017/12/MongoDB-Data-Insertion.png 539w, /wp-content/uploads/2017/12/MongoDB-Data-Insertion-300x199.png 300w, /wp-content/uploads/2017/12/MongoDB-Data-Insertion-400x265.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-12590" class="wp-caption-text">MongoDB Data Insertion</p></div>
<p>If you have noticed, you can see there are an another property names &#8220;_id&#8221; in our database collection. This is a unique id generated by MongoDB for us, so no need to think about it.</p>
<h3><em>Todo</em></h3>
<p>As the purpose of this article is to show how we can insert a data to MongoDB, I called the save method right after the database is connected. In our real life, this is not a recommended way. You must create an Ajax post request and handle the same. I am leaving that task to you. Please try to do that and let me know. I would love to hear back from you.</p>
<h3><span id="conclusion">Conclusion</span></h3>
<p>Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><span id="your-turn-what-do-you-think">Your turn. What do you think?</span></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/using-mongodb-on-node-js-application-using-mongoose/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Upload Files Or Images To Server Using Node JS</title>
		<link>https://sibeeshpassion.com/upload-files-or-images-to-server-using-node-js/</link>
					<comments>https://sibeeshpassion.com/upload-files-or-images-to-server-using-node-js/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sat, 10 Dec 2016 12:43:33 +0000</pubDate>
				<category><![CDATA[Node JS]]></category>
		<category><![CDATA[Express JS Package]]></category>
		<category><![CDATA[Multer Package]]></category>
		<category><![CDATA[Server Side Upload Using Node JS]]></category>
		<category><![CDATA[Upload in Node JS]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11967</guid>

					<description><![CDATA[[toc] Introduction In this post, we will see how we can upload files or images to the server using Node JS. Here we are going to use Visual Studio for our development and preceding NPM packages for our easy development. express multer body-parser We will briefly explain the use of these packages. As you all know Node JS is a runtime environment built on Chrome&#8217;s V8 JavaScript engine for server-side and networking application. And it is an open source which supports cross platforms. Node JS applications are written in pure JavaScript. If you are new to Node JS, I strongly [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this post, we will see how we can upload files or images to the server using <a href="http://sibeeshpassion.com/category/Node-JS/" target="_blank" rel="noopener">Node JS</a>. Here we are going to use <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> for our development and preceding NPM packages for our easy development.</p>
<ul>
<li>express</li>
<li>multer</li>
<li>body-parser</li>
</ul>
<p>We will briefly explain the use of these packages. As you all know Node JS is a runtime environment built on Chrome&#8217;s V8 JavaScript engine for server-side and networking application. And it is an open source which supports cross platforms. Node JS applications are written in pure <a href="http://sibeeshpassion.com/category/javascript/" target="_blank" rel="noopener">JavaScript</a>. If you are new to Node JS, I strongly recommend you to read my previous posts about Node JS <a href="http://sibeeshpassion.com/category/node-js/" target="_blank" rel="noopener">here</a>.</p>
<h2><strong>Download source code</strong></h2>
<p>You can always download the source code from MSDN <a href="https://code.msdn.microsoft.com/Upload-Files-Or-To-Server-15f69aaa" target="_blank" rel="noopener">Upload Files Or Images To Server Using Node JS</a> or you can clone from <a href="https://github.com/SibeeshVenu/NodeJS_File_Upload">Github</a></p>
<h2><strong>Background</strong></h2>
<p>A few years back if you need to upload any files or images to the server, you were completely depended on server side languages like <a href="http://sibeeshpassion.com/category/csharp/" target="_blank" rel="noopener">C#</a> and <a href="http://sibeeshpassion.com/category/PHP/" target="_blank" rel="noopener">PHP</a>. Everything is changed after the revolution of <a href="http://sibeeshpassion.com/category/node-js/" target="_blank" rel="noopener">Node JS</a>. Here I will show you how to upload the files to the server using Node JS, without writing even a single line of server-side code. I hope you will like this.</p>
<h2>Using the code</h2>
<h3><strong>Create a Blank Node JS Web Application</strong></h3>
<p>Create a blank Node JS web application.</p>
<div id="attachment_11968" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/New_Node_JS_Web_Application.png"><img decoding="async" aria-describedby="caption-attachment-11968" class="size-large wp-image-11968" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/New_Node_JS_Web_Application-1024x709.png" alt="new_node_js_web_application" width="634" height="439" srcset="/wp-content/uploads/2016/12/New_Node_JS_Web_Application-1024x709.png 1024w, /wp-content/uploads/2016/12/New_Node_JS_Web_Application-300x208.png 300w, /wp-content/uploads/2016/12/New_Node_JS_Web_Application-768x532.png 768w, /wp-content/uploads/2016/12/New_Node_JS_Web_Application-160x110.png 160w, /wp-content/uploads/2016/12/New_Node_JS_Web_Application-400x277.png 400w, /wp-content/uploads/2016/12/New_Node_JS_Web_Application-866x600.png 866w, /wp-content/uploads/2016/12/New_Node_JS_Web_Application.png 515w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11968" class="wp-caption-text">new_node_js_web_application</p></div>
<h3><strong>Set Up Dependencies in package.json</strong></h3>
<p>To get started, we will set up our dependencies first. To do so, please open your package.json file and paste the preceding code.</p>
<p>[js]<br />
{<br />
&#8220;name&#8221;: &#8220;node_js_file_upload&#8221;,<br />
&#8220;version&#8221;: &#8220;0.0.1&#8221;,<br />
&#8220;description&#8221;: &#8220;Node_JS_File_Upload&#8221;,<br />
&#8220;main&#8221;: &#8220;server.js&#8221;,<br />
&#8220;dependencies&#8221;: {<br />
&#8220;body-parser&#8221;: &#8220;^1.15.2&#8221;,<br />
&#8220;express&#8221;: &#8220;^4.14.0&#8221;,<br />
&#8220;multer&#8221;: &#8220;^1.2.0&#8221;<br />
},<br />
&#8220;author&#8221;: {<br />
&#8220;name&#8221;: &#8220;Sibeesh&#8221;<br />
}<br />
}<br />
[/js]</p>
<p>Now, run the NPM install command as follows.</p>
<p>[csharp]<br />
npm install<br />
[/csharp]</p>
<p>Once you run the command, you can see that the dependencies are installed in the solution.</p>
<div id="attachment_11969" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/NPM-Packages-e1481366627834.png"><img decoding="async" aria-describedby="caption-attachment-11969" class="size-full wp-image-11969" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/NPM-Packages-e1481366627834.png" alt="npm-packages" width="634" height="624" srcset="/wp-content/uploads/2016/12/NPM-Packages-e1481366627834.png 363w, /wp-content/uploads/2016/12/NPM-Packages-e1481366627834-300x295.png 300w, /wp-content/uploads/2016/12/NPM-Packages-e1481366627834-400x394.png 400w, /wp-content/uploads/2016/12/NPM-Packages-e1481366627834-610x600.png 610w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11969" class="wp-caption-text">npm-packages</p></div>
<p>Now we can understand what are these dependencies used for.</p>
<ul>
<li>express</li>
</ul>
<p>As per the <a href="https://expressjs.com/" target="_blank" rel="noopener">Express Team</a>, Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.Express provides a thin layer of fundamental web application features, without obscuring Node.js features that you know and love. You can always learn more about Express Package <a href="https://expressjs.com/" target="_blank" rel="noopener">here</a></p>
<ul>
<li>multer</li>
</ul>
<p>Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy for maximum efficiency. Please read more about multer package <a href="https://github.com/expressjs/multer" target="_blank" rel="noopener">here.</a></p>
<h3><strong>Start using our dependencies</strong></h3>
<p>You can create the instances of our dependencies as follows.</p>
<p>[js]<br />
var Express = require(&#8216;express&#8217;);<br />
var multer = require(&#8216;multer&#8217;);<br />
var bodyParser = require(&#8216;body-parser&#8217;);<br />
var app = Express();<br />
app.use(bodyParser.json());<br />
[/js]</p>
<p>Then, it is time to create a storage which says where and how the files/images should be saved.</p>
<p>[js]<br />
var Storage = multer.diskStorage({<br />
destination: function (req, file, callback) {<br />
callback(null, &#8220;./Images&#8221;);<br />
},<br />
filename: function (req, file, callback) {<br />
callback(null, file.fieldname + &#8220;_&#8221; + Date.now() + &#8220;_&#8221; + file.originalname);<br />
}<br />
});<br />
[/js]</p>
<p>Each file contains the following information:</p>
<p><em>fieldname :</em> Field name specified in the form<br />
<em>originalname :</em> Name of the file on the user&#8217;s computer<br />
<em>encoding :</em> Encoding type of the file<br />
<em>mimetype :</em> Mime type of the file<br />
<em>size :</em> Size of the file in bytes<br />
<em>destination :</em> The folder to which the file has been saved<br />
<em>filename :</em> The name of the file within the destination<br />
<em>path :</em> The full path to the uploaded file<br />
<em>buffer :</em> A Buffer of the entire file</p>
<p>Now please create multer object as follows.</p>
<p>[js]<br />
var upload = multer({ storage: Storage }).array(&#8220;imgUploader&#8221;, 3); //Field name and max count<br />
[/js]</p>
<p>Here multer accepts the storage we created in our previous step as the parameter. The function [js]array(fieldname[, maxCount])[/js]<br />
accept an array of files, all with the name fieldname.</p>
<p>Now it is time to write our post and get action.</p>
<p>[js]<br />
app.get(&#8220;/&#8221;, function (req, res) {<br />
res.sendFile(__dirname + &#8220;/index.html&#8221;);<br />
});</p>
<p>app.post(&#8220;/api/Upload&#8221;, function (req, res) {<br />
upload(req, res, function (err) {<br />
if (err) {<br />
return res.end(&#8220;Something went wrong!&#8221;);<br />
}<br />
return res.end(&#8220;File uploaded sucessfully!.&#8221;);<br />
});<br />
});<br />
[/js]</p>
<p>Here <em>/api/Upload</em> is the action name we are going to set in out HTML page which we will create soon. And last but not the least, we need to make sure that the app is listening to our particular port, in this case it is port 2000.</p>
<p>[js]<br />
app.listen(2000, function (a) {<br />
console.log(&#8220;Listening to port 2000&#8221;);<br />
});<br />
[/js]</p>
<h3><strong>Create HTML page and set up uploading</strong></h3>
<p>You can create the page as follows with the references of the <em>jquery-3.1.1.min.js</em> and <em>jquery.form.min.js</em>.</p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;</p>
<p>&lt;html xmlns=&#8221;http://www.w3.org/1999/xhtml&#8221;&gt;<br />
&lt;head&gt;<br />
&lt;meta charset=&#8221;utf-8&#8243; /&gt;<br />
&lt;title&gt;Upload images to server using Node JS&lt;/title&gt;<br />
&lt;script src=&#8221;Scripts/jquery-3.1.1.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;Scripts/jquery.form.min.js&#8221;&gt;&lt;/script&gt;</p>
<p>&lt;/head&gt;<br />
&lt;body&gt;<br />
&lt;form id=&#8221;frmUploader&#8221; enctype=&#8221;multipart/form-data&#8221; action=&#8221;api/Upload/&#8221; method=&#8221;post&#8221;&gt;<br />
&lt;input type=&#8221;file&#8221; name=&#8221;imgUploader&#8221; multiple /&gt;<br />
&lt;input type=&#8221;submit&#8221; name=&#8221;submit&#8221; id=&#8221;btnSubmit&#8221; value=&#8221;Upload&#8221; /&gt;<br />
&lt;/form&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>Please be noted that the <em>ecctype </em>for your form must be <em>multipart/form-data</em> and the action must be same as we set in our API.</p>
<h3><strong>Create Ajax submit event</strong></h3>
<p>Now it is time to create our ajax event where we are going to call our API.</p>
<p>[js]<br />
&lt;script&gt;<br />
$(document).ready(function () {<br />
var options = {<br />
beforeSubmit: showRequest, // pre-submit callback<br />
success: showResponse // post-submit callback<br />
};</p>
<p>// bind to the form&#8217;s submit event<br />
$(&#8216;#frmUploader&#8217;).submit(function () {<br />
$(this).ajaxSubmit(options);<br />
// always return false to prevent standard browser submit and page navigation<br />
return false;<br />
});<br />
});</p>
<p>// pre-submit callback<br />
function showRequest(formData, jqForm, options) {<br />
alert(&#8216;Uploading is starting.&#8217;);<br />
return true;<br />
}</p>
<p>// post-submit callback<br />
function showResponse(responseText, statusText, xhr, $form) {<br />
alert(&#8216;status: &#8216; + statusText + &#8216;\n\nresponseText: \n&#8217; + responseText );<br />
}<br />
&lt;/script&gt;<br />
[/js]</p>
<blockquote><p><em>ajaxSubmit</em> function is part of the plugin <em>jquery.form.min.js</em>, so please make sure that you have included it.</p></blockquote>
<h3><strong>Run your application</strong></h3>
<p>Now please run your application. Before running your application, you can always set your script file as your start up file, to set it, please right click on your project and click on properties.</p>
<div id="attachment_11970" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Set-start-up-file.png"><img decoding="async" aria-describedby="caption-attachment-11970" class="size-large wp-image-11970" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Set-start-up-file-1024x383.png" alt="set-start-up-file" width="634" height="237" srcset="/wp-content/uploads/2016/12/Set-start-up-file-1024x383.png 1024w, /wp-content/uploads/2016/12/Set-start-up-file-300x112.png 300w, /wp-content/uploads/2016/12/Set-start-up-file-768x288.png 768w, /wp-content/uploads/2016/12/Set-start-up-file-400x150.png 400w, /wp-content/uploads/2016/12/Set-start-up-file.png 1509w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11970" class="wp-caption-text">set-start-up-file</p></div>
<p>Now you can open your command prompt, you can manually locate your project in command prompt or you can use the &#8216;Open command prompt here&#8217; option. To select, please right click on your project and select the option as follows.</p>
<div id="attachment_11971" style="width: 783px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Open_command_prompt_here_option.png"><img decoding="async" aria-describedby="caption-attachment-11971" class="size-full wp-image-11971" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Open_command_prompt_here_option-e1481369183917.png" alt="open_command_prompt_here_option" width="773" height="1008" srcset="/wp-content/uploads/2016/12/Open_command_prompt_here_option-e1481369183917.png 274w, /wp-content/uploads/2016/12/Open_command_prompt_here_option-e1481369183917-230x300.png 230w, /wp-content/uploads/2016/12/Open_command_prompt_here_option-e1481369183917-400x522.png 400w, /wp-content/uploads/2016/12/Open_command_prompt_here_option-e1481369183917-460x600.png 460w" sizes="(max-width: 773px) 100vw, 773px" /></a><p id="caption-attachment-11971" class="wp-caption-text">open_command_prompt_here_option</p></div>
<p>Now type <em>node server.js</em> in your command prompt which will make sure that your server is running. And if everything is fine, you can see a window as follows.</p>
<div id="attachment_11972" style="width: 593px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Node_server_js_output.png"><img decoding="async" aria-describedby="caption-attachment-11972" class="size-full wp-image-11972" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Node_server_js_output.png" alt="node_server_js_output" width="583" height="414" srcset="/wp-content/uploads/2016/12/Node_server_js_output.png 583w, /wp-content/uploads/2016/12/Node_server_js_output-300x213.png 300w, /wp-content/uploads/2016/12/Node_server_js_output-400x284.png 400w" sizes="(max-width: 583px) 100vw, 583px" /></a><p id="caption-attachment-11972" class="wp-caption-text">node_server_js_output</p></div>
<p>We can run our webpage now as our server is ready, please go to your browser and type the URL as <a href="http://localhost:2000" target="_blank" rel="noopener">http://localhost:2000</a>. Select few files using the file uploader we have created.</p>
<div id="attachment_11973" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Select_fiels_in_file_upload-e1481369767333.png"><img decoding="async" aria-describedby="caption-attachment-11973" class="size-full wp-image-11973" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Select_fiels_in_file_upload-e1481369767333.png" alt="select_fiels_in_file_upload" width="634" height="117" srcset="/wp-content/uploads/2016/12/Select_fiels_in_file_upload-e1481369767333.png 634w, /wp-content/uploads/2016/12/Select_fiels_in_file_upload-e1481369767333-300x55.png 300w, /wp-content/uploads/2016/12/Select_fiels_in_file_upload-e1481369767333-400x74.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11973" class="wp-caption-text">select_fiels_in_file_upload</p></div>
<p>If you click submit, you can see we are calling our method action and the files are uploaded.</p>
<div id="attachment_11974" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/File_uploaded_successfully_-e1481369870966.png"><img decoding="async" aria-describedby="caption-attachment-11974" class="size-full wp-image-11974" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/File_uploaded_successfully_-e1481369870966.png" alt="file_uploaded_successfully_" width="634" height="122" srcset="/wp-content/uploads/2016/12/File_uploaded_successfully_-e1481369870966.png 634w, /wp-content/uploads/2016/12/File_uploaded_successfully_-e1481369870966-300x58.png 300w, /wp-content/uploads/2016/12/File_uploaded_successfully_-e1481369870966-400x77.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11974" class="wp-caption-text">file_uploaded_successfully_</p></div>
<div id="attachment_11975" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/12/Solution_explorer_window_after_saving_files-e1481369985988.png"><img decoding="async" aria-describedby="caption-attachment-11975" class="size-full wp-image-11975" src="http://sibeeshpassion.com/wp-content/uploads/2016/12/Solution_explorer_window_after_saving_files-e1481369985988.png" alt="solution_explorer_window_after_saving_files" width="634" height="603" srcset="/wp-content/uploads/2016/12/Solution_explorer_window_after_saving_files-e1481369985988.png 375w, /wp-content/uploads/2016/12/Solution_explorer_window_after_saving_files-e1481369985988-300x285.png 300w, /wp-content/uploads/2016/12/Solution_explorer_window_after_saving_files-e1481369985988-400x380.png 400w, /wp-content/uploads/2016/12/Solution_explorer_window_after_saving_files-e1481369985988-631x600.png 631w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11975" class="wp-caption-text">solution_explorer_window_after_saving_files</p></div>
<p>You can always download the source code attached to see the complete code and application. Happy coding!.</p>
<h2><strong>See also</strong></h2>
<ul>
<li><a href="https://www.npmjs.com/package/multer" target="_blank" rel="noopener">Multer Package for Node JS</a></li>
<li><a href="https://expressjs.com/" target="_blank" rel="noopener">Express JS Package for Node JS</a></li>
<li><a href="https://github.com/expressjs/body-parser" target="_blank" rel="noopener">Body Parser Package for Node JS</a></li>
</ul>
<h2><strong>Conclusion</strong></h2>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><strong>Your turn. What do you think?</strong></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/upload-files-or-images-to-server-using-node-js/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>SQL Server CRUD Actions Using Node JS</title>
		<link>https://sibeeshpassion.com/sql-server-crud-actions-using-node-js/</link>
					<comments>https://sibeeshpassion.com/sql-server-crud-actions-using-node-js/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 27 Nov 2016 16:40:21 +0000</pubDate>
				<category><![CDATA[Node JS]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[CRUD in Node JS]]></category>
		<category><![CDATA[Database actions using Node JS]]></category>
		<category><![CDATA[Microsoft SQL Server client for Node JS]]></category>
		<category><![CDATA[MSSQL Node JS]]></category>
		<category><![CDATA[Node JS Application In Visual Studio]]></category>
		<category><![CDATA[SQL Server For Node JS]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11947</guid>

					<description><![CDATA[[toc] Introduction In this post we will see how we can perform CRUD application in our SQL database using Node JS. As you all know Node JS is a run time environment built on Chrome&#8217;s V8 JavaScript engine for server side and networking application. And it is an open source which supports cross platforms. Node JS applications are written in pure JavaScript. If you are new to Node JS, I strongly recommend you to read my previous post about Node JS here. Now let&#8217;s begin. Download source code SQL Server CRUD Actions Using Node JS Background There was a time [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h3>Introduction</h3>
<p>In this post we will see how we can perform CRUD application in our <a href="http://sibeeshpassion.com/category/SQL" target="_blank" rel="noopener">SQL </a> database using <a href="http://sibeeshpassion.com/category/Node-JS/" target="_blank" rel="noopener">Node JS</a>. As you all know Node JS is a run time environment built on Chrome&#8217;s V8 JavaScript engine for server side and networking application. And it is an open source which supports cross platforms. Node JS applications are written in pure <a href="http://sibeeshpassion.com/category/javascript/" target="_blank" rel="noopener">JavaScript</a>. If you are new to Node JS, I strongly recommend you to read my previous post about Node JS <a href="http://sibeeshpassion.com/introduction-to-node-js/" target="_blank" rel="noopener">here</a>. Now let&#8217;s begin.</p>
<h3><strong>Download source code</strong></h3>
<ul>
<li><a href="https://code.msdn.microsoft.com/SQL-Server-CRUD-Actions-6bc910fd" target="_blank" rel="noopener">SQL Server CRUD Actions Using Node JS </a></li>
</ul>
<h3><strong>Background</strong></h3>
<p>There was a time where we developers are depended on any server side languages to perform server side actions, few years back a company called Joyent, Inc brought us a solution for this. That is, we can do the server side actions if you know JavaScript. Because of the wonderful idea behind this, it became a great success. You can do server side actions without knowing a single code related to any server side languages like <a href="http://sibeeshpassion.com/category/csharp/" target="_blank" rel="noopener">C#</a> and <a href="http://sibeeshpassion.com/category/PHP/" target="_blank" rel="noopener">PHP</a>. Here we are going to see how you can do the database actions like Create, Read, Update, Delete using Node JS. I hope you will like this.</p>
<p>Before we start coding our Node JS application, we can set up Node JS tool available for <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank" rel="noopener">Visual Studio</a>.</p>
<h3><strong>Node JS tool for Visual Studio</strong></h3>
<blockquote><p>You can always run your Node JS code by using a command prompt, so setting up this tool is optional. If you install it, you can easily debug and develop Node JS. So I recommend you to install it.</p></blockquote>
<p>To download the tool, please click on this <a href="https://www.visualstudio.com/vs/node-js/" target="_blank" rel="noopener">link</a>. Once you have downloaded the set up file, you can start installing it.</p>
<div id="attachment_11948" style="width: 628px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_tool_for_Visual_Studio.png"><img decoding="async" aria-describedby="caption-attachment-11948" class="size-full wp-image-11948" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_tool_for_Visual_Studio.png" alt="node_js_tool_for_visual_studio" width="618" height="483" srcset="/wp-content/uploads/2016/11/Node_JS_tool_for_Visual_Studio.png 618w, /wp-content/uploads/2016/11/Node_JS_tool_for_Visual_Studio-300x234.png 300w, /wp-content/uploads/2016/11/Node_JS_tool_for_Visual_Studio-400x313.png 400w" sizes="(max-width: 618px) 100vw, 618px" /></a><p id="caption-attachment-11948" class="wp-caption-text">node_js_tool_for_visual_studio</p></div>
<p>So I hope you have installed the application, Now you can create a Node JS application in our Visual Studio.</p>
<h3><strong>Creating Node JS Application In Visual Studio</strong></h3>
<p>You can find an option as Node JS in your Add New Project window as follows. Please click on that and create a new project.</p>
<div id="attachment_11949" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/New_Node_JS_Project.png"><img decoding="async" aria-describedby="caption-attachment-11949" class="size-large wp-image-11949" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/New_Node_JS_Project-1024x709.png" alt="new_node_js_project" width="634" height="439" srcset="/wp-content/uploads/2016/11/New_Node_JS_Project-1024x709.png 1024w, /wp-content/uploads/2016/11/New_Node_JS_Project-300x208.png 300w, /wp-content/uploads/2016/11/New_Node_JS_Project-768x532.png 768w, /wp-content/uploads/2016/11/New_Node_JS_Project-160x110.png 160w, /wp-content/uploads/2016/11/New_Node_JS_Project-400x277.png 400w, /wp-content/uploads/2016/11/New_Node_JS_Project-866x600.png 866w, /wp-content/uploads/2016/11/New_Node_JS_Project.png 515w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11949" class="wp-caption-text">new_node_js_project</p></div>
<p>Now our Visual Studio is ready for coding, but as I mentioned earlier, we are going to use <a href="http://sibeeshpassion.com/category/sql-server/" target="_blank" rel="noopener">SQL Server</a> as our database. So we need to do some configuration related to that too. Let&#8217;s do it now.</p>
<h4><strong>Configure SQL Server For Node JS Development</strong></h4>
<p>You need to make sure that the following service are run.</p>
<ul>
<li>SQL Server</li>
<li>SQL Server Agent (Skip it if you are using SQLEXPRESS</li>
<li>SQL Server Browser</li>
</ul>
<p>To check the status of these service, you can always services by running <em>services.msc</em> in Run command window. Once you are done, you need to enables some protocols and assign a port to it. Now go to your SQL Server Configuration Manager. Most probably you can find the file in this <em>C:\Windows\SysWOW64</em> location, if you cant find it start window.</p>
<div id="attachment_11950" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/SQL_Server_Manager_Location-e1480260854402.png"><img decoding="async" aria-describedby="caption-attachment-11950" class="size-full wp-image-11950" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/SQL_Server_Manager_Location-e1480260854402.png" alt="sql_server_manager_location" width="634" height="206" srcset="/wp-content/uploads/2016/11/SQL_Server_Manager_Location-e1480260854402.png 634w, /wp-content/uploads/2016/11/SQL_Server_Manager_Location-e1480260854402-300x97.png 300w, /wp-content/uploads/2016/11/SQL_Server_Manager_Location-e1480260854402-400x130.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11950" class="wp-caption-text">sql_server_manager_location</p></div>
<p>Now go to SQL Server Network Configuration and click on Protocols for SQLEXPRESS(Your SQL Server) and Enable TCP/IP.</p>
<div id="attachment_11951" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Protocols_For_SQL_EXPRESS-e1480261046507.png"><img decoding="async" aria-describedby="caption-attachment-11951" class="size-full wp-image-11951" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Protocols_For_SQL_EXPRESS-e1480261046507.png" alt="protocols_for_sql_express" width="634" height="266" srcset="/wp-content/uploads/2016/11/Protocols_For_SQL_EXPRESS-e1480261046507.png 634w, /wp-content/uploads/2016/11/Protocols_For_SQL_EXPRESS-e1480261046507-300x126.png 300w, /wp-content/uploads/2016/11/Protocols_For_SQL_EXPRESS-e1480261046507-400x168.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11951" class="wp-caption-text">protocols_for_sql_express</p></div>
<p>Now right click and click on Properties on TCP/IP. Go to to IP Addresses and assign port for all the IP.</p>
<div id="attachment_11952" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Assigning_TCP_IP_Port_In_SQL_Server.png"><img decoding="async" aria-describedby="caption-attachment-11952" class="size-large wp-image-11952" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Assigning_TCP_IP_Port_In_SQL_Server-1024x707.png" alt="assigning_tcp_ip_port_in_sql_server" width="634" height="438" srcset="/wp-content/uploads/2016/11/Assigning_TCP_IP_Port_In_SQL_Server-1024x707.png 1024w, /wp-content/uploads/2016/11/Assigning_TCP_IP_Port_In_SQL_Server-300x207.png 300w, /wp-content/uploads/2016/11/Assigning_TCP_IP_Port_In_SQL_Server-768x530.png 768w, /wp-content/uploads/2016/11/Assigning_TCP_IP_Port_In_SQL_Server-160x110.png 160w, /wp-content/uploads/2016/11/Assigning_TCP_IP_Port_In_SQL_Server-400x276.png 400w, /wp-content/uploads/2016/11/Assigning_TCP_IP_Port_In_SQL_Server-869x600.png 869w, /wp-content/uploads/2016/11/Assigning_TCP_IP_Port_In_SQL_Server.png 517w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11952" class="wp-caption-text">assigning_tcp_ip_port_in_sql_server</p></div>
<p>If have done it, it is time to set up our database and insert some data. Please do not forget to restart your service, as it is mandatory to get updated the changes we have done in the configurations.</p>
<div id="attachment_11954" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Restart_SQL_EXPRESS.png"><img decoding="async" aria-describedby="caption-attachment-11954" class="size-large wp-image-11954" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Restart_SQL_EXPRESS-1024x595.png" alt="restart_sql_express" width="634" height="368" srcset="/wp-content/uploads/2016/11/Restart_SQL_EXPRESS-1024x595.png 1024w, /wp-content/uploads/2016/11/Restart_SQL_EXPRESS-300x174.png 300w, /wp-content/uploads/2016/11/Restart_SQL_EXPRESS-768x446.png 768w, /wp-content/uploads/2016/11/Restart_SQL_EXPRESS-400x233.png 400w, /wp-content/uploads/2016/11/Restart_SQL_EXPRESS-1032x600.png 1032w, /wp-content/uploads/2016/11/Restart_SQL_EXPRESS.png 614w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11954" class="wp-caption-text">restart_sql_express</p></div>
<h4><strong>Creating database</strong></h4>
<p>Here I am creating a database with name &#8220;TrialDB&#8221;, you can always create a DB by running the query given below.</p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object: Database [TrialDB] Script Date: 20-11-2016 03:54:53 PM ******/<br />
CREATE DATABASE [TrialDB]<br />
CONTAINMENT = NONE<br />
ON PRIMARY<br />
( NAME = N&#8217;TrialDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB.mdf&#8217; , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )<br />
LOG ON<br />
( NAME = N&#8217;TrialDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB_log.ldf&#8217; , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET COMPATIBILITY_LEVEL = 130<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_DEFAULT GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECOVERY SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TARGET_RECOVERY_TIME = 60 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DELAYED_DURABILITY = DISABLED<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUERY_STORE = OFF<br />
GO</p>
<p>USE [TrialDB]<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET READ_WRITE<br />
GO<br />
[/sql]</p>
<p><strong>Create a table and insert data in database</strong></p>
<p>To create a table, you can run the query below.</p>
<p>[sql]<br />
USE [TrialDB]<br />
GO</p>
<p>/****** Object: Table [dbo].[Course] Script Date: 20-11-2016 03:57:30 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[Course](<br />
[CourseID] [int] NOT NULL,<br />
[CourseName] [nvarchar](50) NOT NULL,<br />
[CourseDescription] [nvarchar](100) NULL,<br />
CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED<br />
(<br />
[CourseID] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Now we can insert few data to our newly created table.</p>
<p>[sql]<br />
USE [TrialDB]<br />
GO</p>
<p>INSERT INTO [dbo].[Course]<br />
([CourseID]<br />
,[CourseName]<br />
,[CourseDescription])<br />
VALUES<br />
(1<br />
,&#8217;C#&#8217;<br />
,&#8217;Learn C# in 7 days&#8217;)<br />
INSERT INTO [dbo].[Course]<br />
([CourseID]<br />
,[CourseName]<br />
,[CourseDescription])<br />
VALUES<br />
(2<br />
,&#8217;Asp.Net&#8217;<br />
,&#8217;Learn Asp.Net in 7 days&#8217;)<br />
INSERT INTO [dbo].[Course]<br />
([CourseID]<br />
,[CourseName]<br />
,[CourseDescription])<br />
VALUES<br />
(3<br />
,&#8217;SQL&#8217;<br />
,&#8217;Learn SQL in 7 days&#8217;)<br />
INSERT INTO [dbo].[Course]<br />
([CourseID]<br />
,[CourseName]<br />
,[CourseDescription])<br />
VALUES<br />
(4<br />
,&#8217;JavaScript&#8217;<br />
,&#8217;Learn JavaScript in 7 days&#8217;)<br />
GO<br />
[/sql]</p>
<p>So our data is ready, that means we are all set to write our Node JS application. Go to the application we created and you can see a JS file there, normally named as <em>server.js</em>. Here I am going to change the name as <em>App.js</em>.</p>
<h4><strong>MSSQL &#8211; Microsoft SQL Server client for Node.js</strong></h4>
<p>You can find many packages for our day to day life in Node JS, what you need to do all is , just install that package and start using it. Here we are going to use a package called MSSQL.</p>
<p>Node-MSSQL</p>
<ul>
<li>Has unified interface for multiple TDS drivers.</li>
<li>Has built-in connection pooling.</li>
<li>Supports built-in JSON serialization introduced in SQL Server 2016.</li>
<li>Supports Stored Procedures, Transactions, Prepared Statements, Bulk Load and TVP.</li>
<li>Supports serialization of Geography and Geometry CLR types.</li>
<li>Has smart JS data type to SQL data type mapper.</li>
<li>Supports Promises, Streams and standard callbacks.</li>
<li>Supports ES6 tagged template literals.</li>
<li>Is stable and tested in production environment.</li>
<li>Is well documented.</li>
</ul>
<p>You can find more about the package <a href="https://www.npmjs.com/package/mssql" target="_blank" rel="noopener">here</a>. You can easily install this package by running the following command in your Nuget Package Manager Console.</p>
<p>[csharp]<br />
npm install mssql<br />
[/csharp]</p>
<div id="attachment_11953" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/MSSQL_Node_JS_Install.png"><img decoding="async" aria-describedby="caption-attachment-11953" class="size-large wp-image-11953" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/MSSQL_Node_JS_Install-1024x236.png" alt="mssql_node_js_install" width="634" height="146" srcset="/wp-content/uploads/2016/11/MSSQL_Node_JS_Install-1024x236.png 1024w, /wp-content/uploads/2016/11/MSSQL_Node_JS_Install-300x69.png 300w, /wp-content/uploads/2016/11/MSSQL_Node_JS_Install-768x177.png 768w, /wp-content/uploads/2016/11/MSSQL_Node_JS_Install-400x92.png 400w, /wp-content/uploads/2016/11/MSSQL_Node_JS_Install.png 1466w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11953" class="wp-caption-text">mssql_node_js_install</p></div>
<p>Now we can load this package by using a function called require.</p>
<p>[js]<br />
//MSSQL Instance Creation<br />
var sqlInstance = require(&#8220;mssql&#8221;);<br />
[/js]</p>
<p>Then, you can set the database configurations as preceding.</p>
<p>[js]<br />
/Database configuration<br />
var setUp = {<br />
server: &#8216;localhost&#8217;,<br />
database: &#8216;TrialDB&#8217;,<br />
user: &#8216;sa&#8217;,<br />
password: &#8216;sa&#8217;,<br />
port: 1433<br />
};<br />
[/js]</p>
<p>Once you have a configuration set up, you can connect your database by using connect() function.</p>
<p>[js]<br />
sqlInstance.connect(setUp)<br />
[/js]</p>
<p>Now we can perform the CRUD operations. Are you ready?</p>
<h4><strong>Select all the data from database using Node JS</strong></h4>
<p>[js]<br />
// To retrieve all the data &#8211; Start<br />
new sqlInstance.Request()<br />
.query(&#8220;select * from Course&#8221;)<br />
.then(function (dbData) {<br />
if (dbData == null || dbData.length === 0)<br />
return;<br />
console.dir(&#8216;All the courses&#8217;);<br />
console.dir(dbData);<br />
})<br />
.catch(function (error) {<br />
console.dir(error);<br />
});</p>
<p>// To retrieve all the data &#8211; End<br />
[/js]</p>
<p>Now run your application and see the output as preceding.</p>
<div id="attachment_11955" style="width: 593px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Select_All_Data_From_Database.png"><img decoding="async" aria-describedby="caption-attachment-11955" class="size-full wp-image-11955" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Select_All_Data_From_Database.png" alt="node_js_select_all_data_from_database" width="583" height="414" srcset="/wp-content/uploads/2016/11/Node_JS_Select_All_Data_From_Database.png 583w, /wp-content/uploads/2016/11/Node_JS_Select_All_Data_From_Database-300x213.png 300w, /wp-content/uploads/2016/11/Node_JS_Select_All_Data_From_Database-400x284.png 400w" sizes="(max-width: 583px) 100vw, 583px" /></a><p id="caption-attachment-11955" class="wp-caption-text">node_js_select_all_data_from_database</p></div>
<h4><strong>Select data with where condition from database using Node JS</strong></h4>
<p>You can always select a particular record by giving an appropriate select query as follows.</p>
<p>[js]<br />
// To retrieve specicfic data &#8211; Start<br />
var value = 2;<br />
new sqlInstance.Request()<br />
.input(&#8220;param&#8221;, sqlInstance.Int, value)<br />
.query(&#8220;select * from Course where CourseID = @param&#8221;)<br />
.then(function (dbData) {<br />
if (dbData == null || dbData.length === 0)<br />
return;<br />
console.dir(&#8216;Course with ID = 2&#8217;);<br />
console.dir(dbData);<br />
})<br />
.catch(function (error) {<br />
console.dir(error);<br />
});<br />
// To retrieve specicfic data &#8211; End<br />
[/js]</p>
<p>So what would be the output of the above code? Any idea?</p>
<div id="attachment_11956" style="width: 593px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Select_Particular_Data_From_Database.png"><img decoding="async" aria-describedby="caption-attachment-11956" class="size-full wp-image-11956" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Select_Particular_Data_From_Database.png" alt="node_js_select_particular_data_from_database" width="583" height="414" srcset="/wp-content/uploads/2016/11/Node_JS_Select_Particular_Data_From_Database.png 583w, /wp-content/uploads/2016/11/Node_JS_Select_Particular_Data_From_Database-300x213.png 300w, /wp-content/uploads/2016/11/Node_JS_Select_Particular_Data_From_Database-400x284.png 400w" sizes="(max-width: 583px) 100vw, 583px" /></a><p id="caption-attachment-11956" class="wp-caption-text">node_js_select_particular_data_from_database</p></div>
<h4><strong>Insert data to database using Node JS</strong></h4>
<p>We can always perform some insert query too using Node JS, the difference will be here is, as we have Transactions in SQL we will include that too here. Following code performs an insert operation.</p>
<p>[js]<br />
// Insert data &#8211; Start<br />
var dbConn = new sqlInstance.Connection(setUp,<br />
function (err) {<br />
var myTransaction = new sqlInstance.Transaction(dbConn);<br />
myTransaction.begin(function (error) {<br />
var rollBack = false;<br />
myTransaction.on(&#8216;rollback&#8217;,<br />
function (aborted) {<br />
rollBack = true;<br />
});<br />
new sqlInstance.Request(myTransaction)<br />
.query(&#8220;INSERT INTO [dbo].[Course] ([CourseName],[CourseDescription]) VALUES (&#8216;Node js&#8217;, &#8216;Learn Node JS in 7 days&#8217;)&#8221;,<br />
function (err, recordset) {<br />
if (err) {<br />
if (!rollBack) {<br />
myTransaction.rollback(function (err) {<br />
console.dir(err);<br />
});<br />
}<br />
} else {<br />
myTransaction.commit().then(function (recordset) {<br />
console.dir(&#8216;Data is inserted successfully!&#8217;);<br />
}).catch(function (err) {<br />
console.dir(&#8216;Error in transaction commit &#8216; + err);<br />
});<br />
}<br />
});<br />
});<br />
});<br />
// Insert data &#8211; End<br />
[/js]</p>
<p>So let&#8217;s run it and see the output.</p>
<div id="attachment_11957" style="width: 593px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Insert_Data_To_Database.png"><img decoding="async" aria-describedby="caption-attachment-11957" class="size-full wp-image-11957" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Insert_Data_To_Database.png" alt="node_js_insert_data_to_database" width="583" height="414" srcset="/wp-content/uploads/2016/11/Node_JS_Insert_Data_To_Database.png 583w, /wp-content/uploads/2016/11/Node_JS_Insert_Data_To_Database-300x213.png 300w, /wp-content/uploads/2016/11/Node_JS_Insert_Data_To_Database-400x284.png 400w" sizes="(max-width: 583px) 100vw, 583px" /></a><p id="caption-attachment-11957" class="wp-caption-text">node_js_insert_data_to_database</p></div>
<h4><strong>Delete data from database using Node JS</strong></h4>
<p>As we performed insert operation, we can do the same for delete operation as below.</p>
<p>[js]<br />
// Delete data &#8211; Start<br />
var delValue = 4;<br />
var dbConn = new sqlInstance.Connection(setUp,<br />
function (err) {<br />
var myTransaction = new sqlInstance.Transaction(dbConn);<br />
myTransaction.begin(function (error) {<br />
var rollBack = false;<br />
myTransaction.on(&#8216;rollback&#8217;,<br />
function (aborted) {<br />
rollBack = true;<br />
});<br />
new sqlInstance.Request(myTransaction)<br />
.query(&#8220;DELETE FROM [dbo].[Course] WHERE CourseID=&#8221; + delValue,<br />
function (err, recordset) {<br />
if (err) {<br />
if (!rollBack) {<br />
myTransaction.rollback(function (err) {<br />
console.dir(err);<br />
});<br />
}<br />
} else {<br />
myTransaction.commit().then(function (recordset) {<br />
console.dir(&#8216;Data is deleted successfully!&#8217;);<br />
}).catch(function (err) {<br />
console.dir(&#8216;Error in transaction commit &#8216; + err);<br />
});<br />
}<br />
});<br />
});<br />
});<br />
// Delete data &#8211; End<br />
[/js]</p>
<p>Now run your application and see whether the data is deleted.</p>
<div id="attachment_11958" style="width: 593px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Delete_Data_From_Database.png"><img decoding="async" aria-describedby="caption-attachment-11958" class="size-full wp-image-11958" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Delete_Data_From_Database.png" alt="node_js_delete_data_from_database" width="583" height="414" srcset="/wp-content/uploads/2016/11/Node_JS_Delete_Data_From_Database.png 583w, /wp-content/uploads/2016/11/Node_JS_Delete_Data_From_Database-300x213.png 300w, /wp-content/uploads/2016/11/Node_JS_Delete_Data_From_Database-400x284.png 400w" sizes="(max-width: 583px) 100vw, 583px" /></a><p id="caption-attachment-11958" class="wp-caption-text">node_js_delete_data_from_database</p></div>
<h4><strong>Update data from database using Node JS</strong></h4>
<p>The only action pending here to perform is UPDATE. Am I right? Let&#8217;s do that too.</p>
<p>[js]<br />
// Update data &#8211; Start<br />
var updValue = 3;<br />
var dbConn = new sqlInstance.Connection(setUp,<br />
function (err) {<br />
var myTransaction = new sqlInstance.Transaction(dbConn);<br />
myTransaction.begin(function (error) {<br />
var rollBack = false;<br />
myTransaction.on(&#8216;rollback&#8217;,<br />
function (aborted) {<br />
rollBack = true;<br />
});<br />
new sqlInstance.Request(myTransaction)<br />
.query(&#8220;UPDATE [dbo].[Course] SET [CourseName] = &#8216;Test&#8217; WHERE CourseID=&#8221; + updValue,<br />
function (err, recordset) {<br />
if (err) {<br />
if (!rollBack) {<br />
myTransaction.rollback(function (err) {<br />
console.dir(err);<br />
});<br />
}<br />
} else {<br />
myTransaction.commit().then(function (recordset) {<br />
console.dir(&#8216;Data is updated successfully!&#8217;);<br />
}).catch(function (err) {<br />
console.dir(&#8216;Error in transaction commit &#8216; + err);<br />
});<br />
}<br />
});<br />
});<br />
});<br />
// Update data &#8211; End<br />
[/js]</p>
<p>Here goes the output.</p>
<div id="attachment_11959" style="width: 593px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Update_Data_From_Database.png"><img decoding="async" aria-describedby="caption-attachment-11959" class="size-full wp-image-11959" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Node_JS_Update_Data_From_Database.png" alt="node_js_update_data_from_database" width="583" height="414" srcset="/wp-content/uploads/2016/11/Node_JS_Update_Data_From_Database.png 583w, /wp-content/uploads/2016/11/Node_JS_Update_Data_From_Database-300x213.png 300w, /wp-content/uploads/2016/11/Node_JS_Update_Data_From_Database-400x284.png 400w" sizes="(max-width: 583px) 100vw, 583px" /></a><p id="caption-attachment-11959" class="wp-caption-text">node_js_update_data_from_database</p></div>
<p>You can always download the source code attached to see the complete code and application. Happy coding!.</p>
<h3><strong>See also</strong></h3>
<ul>
<li><a href="https://www.npmjs.com/package/mssql" target="_blank" rel="noopener">MSSQL Package for Node JS</a></li>
<li><a href="https://nodejs.org/en/" target="_blank" rel="noopener">Node js</a></li>
</ul>
<h3><strong>Conclusion</strong></h3>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h3><strong>Your turn. What do you think?</strong></h3>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/sql-server-crud-actions-using-node-js/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Introduction to Node JS</title>
		<link>https://sibeeshpassion.com/introduction-to-node-js/</link>
					<comments>https://sibeeshpassion.com/introduction-to-node-js/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Fri, 19 Jun 2015 16:44:10 +0000</pubDate>
				<category><![CDATA[Node JS]]></category>
		<category><![CDATA[Node JS Introduction]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=5201</guid>

					<description><![CDATA[In this post we will learn about the basics of Node JS. This article explain the process of installing node js in your system and the basic thing you need to do to configure. You can also get an idea of testing the node js by using some piece of code. Some of you might have already tried this. This article is for the one who have never tried Node JS. I hope you will like it. Background Today one of my colleague asked me &#8220;what is Node JS?&#8221;. I could manage with the definition. But it might have not [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will learn about the basics of Node JS. This article explain the process of installing node js in your system and the basic thing you need to do to configure. You can also get an idea of testing the node js by using some piece of code.  Some of you might have already tried this. This article is for the one who have never tried Node JS. I hope you will like it.</p>
<p><strong>Background</strong></p>
<p>Today one of my colleague asked me &#8220;what is Node JS?&#8221;. I could manage with the definition. But it might have not helped him much. So I thought of creating an article and send him the link for his reference. Hereby I am dedicating this article to him.  </p>
<p><strong>What is Node JS?</strong></p>
<li>Node JS is a run time environment for server side and networking application. </li>
<li>It is an open source</li>
<li>It supports cross platforms</li>
<li>Node JS applications are written in pure javascript</li>
<li>It can be run within Node.js environment on WIndows, Linux, IBm etc&#8230;</li>
<p><strong>To start with</strong></p>
<p>To start with Node JS, you need to go to <a href="https://nodejs.org/" target="_blank">https://nodejs.org/</a> and click on install.</p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/node1.PNG" alt="" /></p>
<p>Figure 1: Download</p>
<p>Now a .msi file will be downloading in your system. Please run that once the downloading is over.</p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/node2.PNG" alt="" /></p>
<p>Figure 2: Installation</p>
<p><img decoding="async" src="http://sibeeshpassion.com/content/images/node3.PNG" alt="" /></p>
<p>Figure 3: Installation Continue</p>
<p>Now I hope you have installed Node JS, So what is next? We need to test our node platform right? </p>
<p><strong>Testing Node JS</strong></p>
<p>To check whether our Node JS is working fine, We can create a &#8220;Hello World&#8221; program in two ways. </p>
<li> Directly type message in command window.</li>
<li> Type the message in a js file and execute it in node </li>
<p><strong>Directly type message in command window</strong></p>
<p>Open your command window( Press Window key <img decoding="async" src="http://www.sibeeshpassion.com/content/images/windows-key.gif" alt="" /> + R ), type cmd in the window. Now a window will be opened, you can type your commands over there.</p>
<p><img decoding="async" src="http://www.sibeeshpassion.com/content/images/node4.png" alt="" /></p>
<p>Once you pointed out to your drive as shown in the image, type &#8220;node&#8221; and press enter. Now you can type anything in your console using console.log. Then You will get the output as shown in the above image. </p>
<p>Now you may be thinking why it returns an undefined error!. Am I right?</p>
<p>It is because of, normally Node JS will displays return value of each commands. As you all know console.log does not return anything. So it is displaying &#8216;undefined&#8217;.</p>
<p><strong>Type the message in a js file and execute it in node</strong></p>
<p>Create a js file manually ( To do so, open a notepad, type some content and save it with .js extension. That is all. ) </p>
<p><img decoding="async" src="http://www.sibeeshpassion.com/content/images/node5.png" alt="" /></p>
<p>I typed the content as &#8220;console.log(&#8216;Sibeesh passion welcomes you to the world of Node&#8217;);&#8221; </p>
<p>Now you can execute that JS file as follows.</p>
<p><img decoding="async" src="http://www.sibeeshpassion.com/content/images/node6.png" alt="" /></p>
<p><strong>Conclusion</strong></p>
<p>I hope you will like this article. Please share me your valuable thoughts and comments. Your feedback is always welcomed.</p>
<p>Thanks in advance. Happy coding!</p>
<p>Kindest Regards<br />
<a href="https://plus.google.com/+sibeeshkv" target="_blank">Sibeesh Venu</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://sibeeshpassion.com/introduction-to-node-js/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
