<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Medhanie(Meda) Neguse on Medium]]></title>
        <description><![CDATA[Stories by Medhanie(Meda) Neguse on Medium]]></description>
        <link>https://medium.com/@medan?source=rss-4a8efdfb08f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UWkL4QRmHnvLiIoXPoU2qA.jpeg</url>
            <title>Stories by Medhanie(Meda) Neguse on Medium</title>
            <link>https://medium.com/@medan?source=rss-4a8efdfb08f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:48:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@medan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[RESTful API using Node.js, Express and MongoDB part 3]]></title>
            <link>https://medium.com/@medan/restful-api-using-node-js-express-and-mongodb-part-3-abed9f35ccf2?source=rss-4a8efdfb08f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/abed9f35ccf2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Medhanie(Meda) Neguse]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 00:50:08 GMT</pubDate>
            <atom:updated>2018-02-27T00:54:37.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cQAZ2YrXqmmrsKMFM4-oMw.jpeg" /></figure><p>The following post is divided into two sections. The first section discusses how to setup the notes.js file, and the second section explains the process of testing the API using the postman application. Please note full code for the notes.js file will be posted at the end of the tutorial.</p><h3>Creating RESTful API</h3><p>As it stands, notes.js file only prints “NOTES PAGE”, it is time to create our api and get the information from the database we created. We will use <strong>GET</strong>, <strong>POST</strong>, <strong>PUT</strong> and <strong>DELETE</strong> requests to accomplish the task.</p><h3>Import</h3><p>Import the modules we are going to use in our application. We will import <strong>Express</strong>, R<strong>outer</strong> to perform our requests and <strong>mongojs</strong> to connect to our database.</p><pre>var express = require(&#39;express&#39;);<br>var router = express.Router();<br>var mongojs = require(&#39;mongojs&#39;);</pre><p>Using mogojs create a connection as follows. In order to create the connection we will need the <em>link</em> to our database. To get the link go to the mLab and copy the link first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*o84jEOrmy9jslCanP8rsTg.png" /></figure><p>Add the following code:</p><pre>var db = mongojs(&#39;mongodb://&lt;dbuser&gt;:&lt;dbpassword&gt;@ds139645.mlab.com:39645/notesdb&#39;, [&#39;notes&#39;]);</pre><p>Replace the “&lt;dbuser&gt;” and “&lt;dbpassword&gt;” with the username and password you created. My username is “bob” and the password “bob”:</p><pre>/* mongojs takes two parameters, the first one is the link to the database and the second one is the collection. We created a collection called notes so we put [&#39;notes&#39;].*/</pre><pre>var db = mongojs(&#39;mongodb://bob:bob@ds139645.mlab.com:39645/notesdb&#39;, [&#39;notes&#39;]);</pre><h3>Get all notes</h3><p>To get all the information from our database we will use the Get request using the router variable. Replace the code we put earlier with the following code:</p><pre>/* get all notes from DB */<br>/* using the variable db we created */<br>router.get(&#39;/notes&#39;, function(req, res, next){<br>/* reading from the database using the db variable we created */<br>/* goes in to the notes collection and finds the data - find is a MongoDB function*/<br>db.notes.find(function(err, notes){<br>/* checks if there is error reading the file and prints the error*/<br>if(err){<br>res.send(err);<br>}</pre><pre>/* if there is no error print get the noes and send them to the browser*/<br>res.send(notes);<br>});<br>});</pre><p>I have put comments under the codes to clarify what each line does.</p><p>Save the notes.js file and run node again to check if the data shows in our browser. To check on the browser got to “http://localhost:4000/api/notes”. Make sure to restart the server each time you make changes. If you did everything correct you will see the data from the database in JSON format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*aKPzTKHDHqflXgtp4JaYgQ.png" /></figure><h3>Get a single note</h3><p>To get a single data from the database we will use the same code above, but format it so it takes unique id of the note. Since each not has a unique id we will use the id as our parameter.</p><pre>/* get a single note from the database */<br>/* using the router and get response, we specify a parameter id &quot;:id&quot; */<br>router.get(&#39;/note/:id&#39;, function(req, res, next){<br>/* using the connection db it will fetch a single note by using findOne function - findOne is a MongoDB function*/<br>/* the _id is the id of the note */<br>/* we use the request parameter id to access the note*/<br>db.notes.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, note){<br>/* checks if there is error reading the file and prints the error*/<br>if(err){<br>res.send(err);<br>}</pre><pre>/* if there is no error print get the noes and send them to the browser*/<br>res.send(note);<br>});<br>});</pre><p>To test the above code save the file and restart the server from the command line in order to see the change. In the browser type “http://localhost:4000/api/note/” plus an id of any note you created. Just copy the id from one of the notes and test it. You URL will be now “http://localhost:4000/api/note/ 5a891874f36d2866535e655b” this will give you only one note.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*iVr-FLlMZBRS_cXvPuOZhw.png" /></figure><p>Now let’s create the post, put and delete request to complete our RESTful api. Since we cannot test these requests from our application directly, we will use postman to test them all together at the end.</p><h3>Add a note</h3><p>We use post request in order to add a note in to our database, in order to do that lets use the following code:</p><pre>/* save note using post request */<br>/* we use the request parameter we will add a note to the database */<br>router.post(&#39;/note&#39;, function(req, res, next){<br>/* &quot;req.body&quot; will allow us to get the note from a form */<br>/* body: this is how we get it from the form */<br>var note = req.body;</pre><pre>/* we check or validate the data that comes from the form */<br>if(!note.title){<br>/* if there is error on the data we print an error message using JSON &quot;res.json&quot; */<br>/* status 400 means bad request */<br>res.status(400);<br>res.json({<br>&quot;error&quot;: &quot;Bad Data try again&quot;<br>});<br>/* if there is no error or if the data is good we save it to the database by using save &quot;db.notes.save&quot; */<br>                } else {<br>db.notes.save(note, function(err, note){<br>if(err){<br>res.send(err);<br>}<br>res.send(note);<br>});<br>}<br>});</pre><p>Read the comment above the code if you want to understand what each code does. Let’s continue creating the rest.</p><h3>Update a note</h3><p>We use post in order to update existing note. To update a node use the following code:</p><pre>/* update a note */<br>/* the next makes sure the next function to be executed if there is one */<br>router.put(&#39;/note/:id&#39;, function(req, res, next){</pre><pre>/* &quot;req.body&quot; will allow us to get the note from a form */<br>var note = req.body;<br>/* updateNote represents the updated note, we leave it empty and use the variable inside */<br>var updateNote = {};</pre><pre>/* we check or validate the data */<br>/* if the note title we set the updateNote to the new title we pass in, this will update the title */<br>if(note.title){<br>updateNote.title = note.title;<br>}</pre><pre>/* if the note content we set the content with the new one*/<br>if(note.content){<br>updateNote.content = note.content;<br>}</pre><pre>/* validating the object itself if it is bad or good */<br>if(!updateNote){<br>/* if there is error on the data we print an error message using JSON &quot;res.json&quot; */<br>/* status 400 means bad request */<br>res.status(400);<br>res.json({<br>&quot;error&quot;: &quot;Update error try again&quot;<br>});<br>} else {<br>/* if there is no error or if the data is good we update it to the database by using update &quot;db.notes.update&quot; */<br>db.notes.update({_id: mongojs.ObjectId(req.params.id)}, updateNote, {}, function(err, note){<br>if(err){<br>res.send(err);<br>}<br>res.send(note);<br>});<br>}<br>});</pre><h3>Delete a note</h3><p>As the name represents we use the delete request in order to delete a note for a database. To create a delete request use the following code:</p><pre>/* delete a note */<br>/* we will use a specific id of the note to delete a note &#39;/note/:id&#39; */<br>router.delete(&#39;/note/:id&#39;, function(req, res, next){<br>/* we use the remove method in order to remove a note */<br>db.notes.remove({_id: mongojs.ObjectId(req.params.id)}, function(err, note){<br>if(err){<br>res.send(err);<br>}<br>res.send(note);<br>});<br>});</pre><p>We now created a GET, POST, PUT and DELETE request successfully and our notes.js file is complete. Now we have to test all requests using postman.</p><h3>Here is the full code that goes in to the note.js file:</h3><pre>var express = require(&#39;express&#39;);<br>var router = express.Router();<br>var mongojs = require(&#39;mongojs&#39;);<br>var db = mongojs(&#39;mongodb://bob:<a href="/service/mailto:bob@ds139645.mlab.com">bob@ds139645.mlab.com</a>:39645/notesdb&#39;, [&#39;notes&#39;]);</pre><pre>/* get all notes from DB */<br>/* using the variable db we created  */<br>/* the next makes sure the next function to be executed if there is one*/</pre><pre>router.get(&#39;/notes&#39;, function(req, res, next){</pre><pre>/* reading from the database using the db variable we created */<br>/* using the connection it will fetch the notes collection and finds the data - find is a MongoDB function*/</pre><pre> db.notes.find(function(err, notes){<br>  <br>/* checks if there is error reading the file and prints the error*/<br>  if(err){<br>   res.send(err);<br>  }<br>  <br>/* if there is no error print get the noes and send them to the browser*/<br>  res.send(notes);<br> });<br>});</pre><pre>/* get a single note from the database */<br>/* using the router and get request, we specify a parameter id &quot;:id&quot; */<br>/* since we are getting only one note we change the notes to note */<br>/* we will use a specific id of the note to get the note &#39;/note/:id&#39; */<br>router.get(&#39;/note/:id&#39;, function(req, res, next){<br> <br>/* using the connection db it will fetch a single note by using findOne function - findOne is a MongoDB function*/<br> /* the _id is the id of the note */<br> /* we use the request parameter id to access the note*/<br> db.notes.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, note){<br>  /* checks if there is error reading the file and prints the error*/<br>  if(err){<br>   res.send(err);<br>  }<br>  /* if there is no error print get the noes and send them to the browser*/<br>  res.send(note);<br> });<br>});</pre><pre>/* save note using post request */<br>/* we use the request parameter we will add a note to the database */<br>/* we will use a specific id of the note to save a note &#39;/note/:id&#39; */<br>router.post(&#39;/note&#39;, function(req, res, next){<br> /* &quot;req.body&quot; will allow us to get the note from a form */<br> /* body: this is how we get it from the form */<br> var note = req.body;<br> /* we check or validate the data that comes from the form */<br> if(!note.title){<br>   /* if there is error on the data we print an error message using JSON &quot;res.json&quot; */<br>   /* status 400 means bad request */<br>   res.status(400);<br>   res.json({<br>    &quot;error&quot;: &quot;Bad Data try again&quot;<br>  });<br>  /* if there is no error or if the data is good we save it to the database by using save &quot;db.notes.save&quot; */<br> } else {<br>  /* we use the save method in order to save a note */<br>  db.notes.save(note, function(err, note){<br>   if(err){<br>   res.send(err);<br>  }<br>   res.send(note);<br>  });<br> }<br>});</pre><pre>/* update a note */<br>/* the next makes sure the next function to be executed if there is one*/<br>/* we will use a specific id of the note to update a note &#39;/note/:id&#39; */<br>router.put(&#39;/note/:id&#39;, function(req, res, next){<br> /* &quot;req.body&quot; will allow us to get the note from a form */<br> var note = req.body;<br> /* updateNote represents the updated note, we leave it empty and use the variable inside */<br> var updateNote = {};<br> /* we check or validate the data */<br> /* if the note title we set the updateNote to the new title we pass in, this will update the title */<br> if(note.title){<br>  updateNote.title = note.title;<br> }<br> /* if teh note content we set the content with the new one*/<br> if(note.content){<br>  updateNote.content = note.content;<br> }</pre><pre>/* validating the object itself if it is bad or good */<br> if(!updateNote){<br>  /* if there is error on the data we print an error message using JSON &quot;res.json&quot; */<br>   /* status 400 means bad request */<br>   res.status(400);<br>   res.json({<br>    &quot;error&quot;: &quot;Update error try again&quot;<br>  });<br> } else {<br>  /* if there is no error or if the data is good we update it to the database by using update &quot;db.notes.update&quot; */<br>  /* we use the update method in order to update a note */<br>  db.notes.update({_id: mongojs.ObjectId(req.params.id)}, updateNote, {}, function(err, note){<br>  if(err){<br>   res.send(err);<br>  }<br>  res.send(note);<br> });  <br> } <br>});</pre><pre>/* delete a note */<br>/* we will use a specific id of the note to delete a note &#39;/note/:id&#39; */<br>router.delete(&#39;/note/:id&#39;, function(req, res, next){<br> /* we use the remove method in order to remove a note */<br> db.notes.remove({_id: mongojs.ObjectId(req.params.id)}, function(err, note){<br>  if(err){<br>   res.send(err);<br>  }<br>  res.send(note);<br> });<br>});</pre><pre>/* this makes avilable to other fiels in the application*/<br>module.exports = router;</pre><h3>Postman</h3><p>Postman is a great tool to test API’s. It help us to test our request and response requests easily. There are several tools that help us to test requests and you can use any tool that you prefer. In order to use postman we have to install it to our computer first. Follow the link to download the free version of <a href="https://www.getpostman.com/">postman here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*TQVv2E9guCw5EPPMlSQMKg.png" /></figure><p>Once the download is completed, install it to your computer by running the exe file. When the installation completed, open it and select “Request” from the menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*qjM0FAGpJTrOjk3rtyBUHA.png" /></figure><p>If you want to save the requests for your reference fill in the required fields, but for this tutorial I will cancel it and start using postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*tAzFCkJllnJqDEOz35EB5g.png" /></figure><h3>Testing our API</h3><h3>Testing the GET Request</h3><p>We have already tested our get requests from within our application, but to test it using postman follow the following steps.</p><p>1. Make sure our application is running, if it is not running run the application from the command line by using “node app”.</p><p>2. Once the application is running use the same URL “http://localhost:4000/api/notes” to see all of our notes from the database.</p><p>3. Inside postman paste in the URL, select GET request from the drop-down menu and click send. You should see all of the notes. See figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*TIXjnzBbmKVzVUOoLRyurQ.png" /></figure><p>To test a single note request use one of the id from the notes and follow the steps above. This time your URL will look like this “http://localhost:4000/api/note/5a891890f36d2866535e655c”. Click send after typing the URL and you should see a single note.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*3LAQz6tGRq4PHMaydlMcRg.png" /></figure><h3>Testing the POST Request</h3><p>To test the post request follow these steps:</p><p>1. Use the URL “http://localhost:4000/api/note” since we are adding to the database.</p><p>2. Change the request to POST from the dropdown</p><p>3. Click Headers button and enter <em>Content-Type</em> inside key and <em>application/json</em> inside value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*zibSK6Q-L57WXY9AI9GRLg.png" /></figure><p>4. Select “raw” under the Body tab and add a data that you want to insert to the database.</p><pre>{<br>&quot;title&quot;: &quot;Note four&quot;,<br>&quot;content&quot;: &quot;My not 4 content&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*VYhHv3hDD9xsq0CTHzxypQ.png" /></figure><p>Our request has been successfully added our note without an error. If there is an error it will tell you at the bottom of the result tab. Now you can check the database and see if our new note is added to the collection. Don’t forget to refresh the mLab website to see the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*954aBl5hbz0QyEhgfD6fVQ.png" /></figure><h3>Testing the PUT Request</h3><p>To test the put we will use the same value we added above and change it to say “Note ten” instead of “Note four”. To do that follow this steps;</p><p>1. Change the request to PUT from the dropdown</p><p>2. Click Headers button and enter Content-Type as header and application/json in value.</p><p>3. Select raw from the Body tab and add a data that you want to insert to the database.</p><pre>{<br>&quot;title&quot;: &quot;Note ten&quot;,<br>&quot;content&quot;: &quot;My note 10 content&quot;<br>}</pre><p>4. In order to update a specific note in this case “Note four” to “Note ten” we need the id of Note four. You can copy it from the database or do a get request and copy it.</p><p>5. Use the URL <a href="http://localhost:4000/api/note">http://localhost:4000/api/note</a> plus the id of the note.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*rkIc5zWxbK2Sh_V3By6xXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*5AmsR_7DmklOHK48QcruXA.png" /></figure><p>The post request updated the note successfully with no error. Now if you go and check the database the note is updated to the new value which is “Note ten”.</p><h3>Testing the DELETE Request</h3><p>Let us test the delete request by deleting the note we updated above which is “Note ten”. To delete the note follow these steps:</p><p>1. Change the request to DELETE from the dropdown</p><p>2. Specify the id of the note in the URL</p><p>3. Send the request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*NnYzMnJ_z37Lrcym72u40g.png" /></figure><p>Our delete request is successfully deleted Note ten from the database as expected. You can refresh and check the database to see if the note we created is gone.</p><p>So this is how you create a simple RESTful API using Node.js, Express and MongoDB. I hope I have given you something useful and meaningful throughout these tutorials. If you are confused or any of the codes didn’t make sense, try to dig in to the online documentations. If you see any error or a better way to solve some of the problems in these tutorials, please comment. As a newbie to Node.js, I am open to learn more about it.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abed9f35ccf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RESTful API using Node.js, Express and MongoDB part 2]]></title>
            <link>https://medium.com/@medan/restful-api-using-node-js-express-and-mongodb-part-2-e2b350c16b74?source=rss-4a8efdfb08f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2b350c16b74</guid>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Medhanie(Meda) Neguse]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 00:49:42 GMT</pubDate>
            <atom:updated>2018-02-27T00:53:38.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cQAZ2YrXqmmrsKMFM4-oMw.jpeg" /></figure><p>Before we continue working on the notes.js file we created in part one, let us create the database first. We can create MongoDB database in our local computer, but for this tutorial I am going to use the <a href="https://mlab.com/">mLab</a> service to create the MongoDB database. I am using mLab because it is very fast to setup and straight forward. The actual plans in mLab are very expensive, but we are going to use the <strong>free</strong> sandbox service. Before we start creating our database you need to create an account first if you don’t have one.</p><h3>Create Database</h3><p>After you logged in successfully follow these steps to create the database.</p><ol><li>Under MongoDB Deployments click on “create new”:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*qXBw5JEhApFWOITB4XuYHQ.png" /></figure><p>2. Under Cloud Provider select “Amazon web services” and under Plan type select “SANDBOX” for free service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*1CFAwCAnSrdORMzSGf7uZw.png" /></figure><p>3. Click continue</p><p>4. Select AWS Region and continue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*md_gY4PLnzMpGnEBG_3Xqw.png" /></figure><p>5. Give you database a name. I call mine “notesdb” and click continue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*KvKBbC_iUvLRsewKo8QHNw.png" /></figure><p>6. Click on submit order button to finalize your database creation.</p><p>7. Once it is all done the database you created will be created and becomes green in color. This means we have successfully created our database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Mx3NNsb8o56ZqjAC0CdwLw.png" /></figure><h3>Add User</h3><p>1. Expand the database — click on it</p><p>2. Add user by selecting the Users tab and clicking on the “Add Database User”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*Uo4GCwpqkZaptrXG6erjow.png" /></figure><p>3. Set the username and password for the database: I put “bob” for username and password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*hTDZXcQAxaqCF9ntYZIXog.png" /></figure><p>4. Click create button and create the user.</p><p>5. Now go back to the collection and create your collection. Select the Collection tab and click on Add Collection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*mmZa4XsfPROaO2IqT-EikQ.png" /></figure><p>6. Give a name to your collection. Since we are creating a notes api call it “notes” and click on create button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*yYm80ibiwh4zRUWOtOiy1w.png" /></figure><p>7. Now we have created a notes collection successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*4k7CL7eebwmBJSh9czBIAg.png" /></figure><p>8. Let us populate our collection with data using a JSON format. Open the notes collection by clicking on it. After you open the notes collection click on Add Document button to add data in to our notes collection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*eU6VJMMu5AKXwmE2fLP_aA.png" /></figure><p>9. Our note will have a <strong>title</strong> and <strong>content</strong>. Add a title and content of a note. Make sure it is surrounded by a quotation. I am going to add 3 different notes. You can use my data or you can create your own:</p><pre>{<br>&quot;title&quot;: &quot;Note one&quot;,<br>&quot;content&quot;: &quot;My not 1 content&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*1c7VeOg-K4Ysbw4iILSTYg.png" /></figure><p>10. Click on create and continue to add more data by following step 8: make sure to insert them one by one:</p><pre>{<br>title&quot;: &quot;Note two&quot;,<br>&quot;content&quot;: &quot;My not 2 content&quot;<br>}</pre><pre>{<br>&quot;title&quot;: &quot;Note three&quot;,<br>&quot;content&quot;: &quot;My not 3 content&quot;<br>}</pre><p>11. Once you add the data click on save and go back. We now have data in our notes table. Since I added 3 notes I have 3 data in my notes collection. Please note besides the title and the content we added, there is a third value in the collection. It is the unique id of the notes that is generated by MongoDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ytZDG2A91JCxcJpUXDIXqw.png" /></figure><p>We have successfully created a database using MongoDB. It is time to use it in our application. One information we need from mLab is the link to our database so we can use it access the data in the next tutorial. We can find the link at the home page of mLab. See image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*o84jEOrmy9jslCanP8rsTg.png" /></figure><p>We will use this link in our application by using the mongojs module that we installed at the beginning of this tutorial. We will work on our notes.js file on the next and last part of the tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2b350c16b74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RESTful API using Node.js, Express and MongoDB part 1]]></title>
            <link>https://medium.com/@medan/restful-api-using-node-js-express-and-mongodb-part-1-d2cda8117ccf?source=rss-4a8efdfb08f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2cda8117ccf</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Medhanie(Meda) Neguse]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 00:49:12 GMT</pubDate>
            <atom:updated>2018-02-27T00:52:49.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cQAZ2YrXqmmrsKMFM4-oMw.jpeg" /></figure><p>In this tutorial I will develop a RESTful API using Node.js, for MongoDB we will use mLab deployment, Express framework for our routing API’s and Postman to test our API we developed.</p><p>The tutorial will have three parts and discuss the following:</p><ul><li>Part One: <strong>Setting up Node.js</strong></li><li>Part Two: <strong>Creating MongoDB database using mLab</strong></li><li>Part Three: <strong>Create notes API and will test the API using Postman</strong></li></ul><h3>Setting our project using Node.js</h3><p>In order to do this you need to have Node.js installed in your computer. If you don’t have Node instated on your computer you need to install it first. You can see <a href="https://medium.com/@medan/how-to-set-up-and-run-node-js-for-beginners-a9473a25f6f6">here</a> on how to install Node.js to your computer.</p><h3>Creating a project</h3><p>Create a folder in your computer anywhere you want. I am going to call my folder “noteManager”. Once you created a folder, open it in the command line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*AO_Dfqta_FEzdHnngghq6Q.png" /></figure><h3>package.json file</h3><p>Create a package.json file using the command line. Use the following command:</p><pre>npm init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*EIxtX22Ehz4jF__fG_OETQ.png" /></figure><p>You can have values of your own to create the package.json file. As you can see above I have created mine with few changes to the default value. in the above example the only change I did is to the main entry point, I called mine “app.js” by default it is set to “index.js”. It will ask you if it is ok to create the file and you will say yes by pressing enter. If you did it correctly, you will see a file called package.json file inside your project folder. If you are a bit confused, by the above instruction, you can follow this <a href="https://docs.npmjs.com/files/package.json">link </a>to learn more about creating package.json file.</p><h3>Installing dependencies</h3><p>Let us install our dependencies using NPM. For this application we will install <strong>Express</strong> framework, <strong>body-parser</strong> in order to accept data from a form and parse it to the database, <strong>EJS</strong> as our template engine and <strong>mogojs</strong> to help us interact with MongoDB. We can install them one by one or install them at the same time using the following command:</p><pre>npm install express body-parser ejs mogojs — save</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Wi4aX1DrHyRzvk9d4cSMbA.png" /></figure><p>When the installation finished check the package.json file we created earlier, it will have the dependencies we just installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*EW5BeJlf8O-ArYMmBV-2iA.png" /></figure><p>Now that we have installed dependencies, let us setup our server using the app.js file. Please note, yours could have a different main entry point name, it depends on how you set it up. Since I set my main to “app.js” I will use app.js.</p><h3>Creating the app.js file and folders</h3><p>The app.js file is going to be our main back-end sever file. Create the file inside the project first and open it in a text editor. I am using <a href="https://notepad-plus-plus.org/">Notepad++</a> as my text editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*MMkP0v1sOXlatUoahw2Jrw.png" /></figure><p>After opening the file in your text editor, setup the server and routes using the following code. I will try to explain the codes step by step so it is easy to understand and I will put them all together at the end.</p><h3>Import</h3><p>Import the modules we need to use in this application by using the following code:</p><pre>var express = require(&#39;express&#39;);<br>/* helps for file system path, it comes with the core */<br>var path = require(&#39;path&#39;);<br>/* body-parser accept data through a form and parse it to the DB */<br>var bodyParser = require(&#39;body-parser&#39;);<br>/* main app variable for express */<br>var app = express();</pre><h3>Folders</h3><p>We are going to create a folder called “routes” and inside the folder we will create two files called “index.js” for our landing page and “notes.js” for the note api. We will work on the files later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*34tMUTqWRn5vqix9gkq-bA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*dkydrwQSaxrn5T2QerC9ag.png" /></figure><p>After creating the folder, create folder path inside the app.js file by using the following code:</p><pre>/* create folders path */<br>/* we are creating two folders 1. index for our home page */<br>/* another one for or notes */<br>var index = require(&#39;./routes/index&#39;);<br>var notes = require(&#39;./routes/notes&#39;);</pre><h3>View Engines</h3><p>Template engines helps us to use a static template in our application. The template engine transforms our template to HTML file that will be sent to the client by changing the variables in our files in to an actual values. There are several template engines to be used with express, we are going to use EJS as our template engine. For further information please <a href="https://expressjs.com/en/guide/using-template-engines.html">refer to this link</a>.</p><p>Before specifying, we need to create a folder called views. The views folder will be used for our client views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*3IoxHoUZvBjriFeeF2MlqQ.png" /></figure><p>After creating the views folder, use the following code:</p><pre>/* View Engine system will be used for the view in our app */<br>/* We are telling the system which folder to use for our views */<br>app.set(&#39;views&#39;, path.join(__dirname, &#39;views&#39;));<br>/* specify the engine to ejs */<br>app.set(&#39;view engine&#39;, &#39;ejs&#39;);<br>/* we are telling the system to render html extensions */<br>app.engine(&#39;html&#39;, require(&#39;ejs&#39;).renderFile);</pre><h3>Middleware</h3><p>Middleware functions are function that have access to objects like request(req), response(res) and the next function in the application’s request response cycle. Some of the middleware functions can perform the following tasks: execute code, make changes to request and response objects, and end response-request cycle. <a href="https://expressjs.com/en/guide/using-middleware.html">Read here for more information</a>.</p><p>There are few build-in middleware functions in Express but, we are going to use a third party middleware <a href="https://www.npmjs.com/package/body-parser">body-parser</a> in our application. To set the middleware we will use the body-parser that we installed earlier.</p><pre>/* we will be able to parse JSON */<br>app.use(bodyParser.json());<br>app.use(bodyParser.urlencoded({extended: false}));</pre><h3>Routes</h3><p>In order to use the routes we created earlier, we have to specify it to the system to use the folders. We created two files <strong>index</strong> and <strong>notes</strong> to use them put the following code:</p><pre>/* this are the routes we are going to use */<br>/* the &#39;/&#39; is the landing page or the home page, it means root */<br>app.use(&#39;/&#39;, index);<br>/* we are using the &#39;/api&#39; for our notes route */<br>app.use(&#39;/api&#39;, notes);</pre><h3>Listen using port</h3><p>We have to specify a port and use the listen function to run our application in the browser. To do that use the following code:</p><pre>/* port number to listen to */<br>var port = 4000;<br>/* listener to the port we specified which is 4000 */<br>/* if our port is correct and listens it will display &#39;Server started on 4000&#39; */<br>app.listen(port, function(){<br>/* checking if the server is running */<br>console.log(&#39;Server started on &#39; + port);<br>});</pre><p>Now we have completed with our setup to the app.js file. But before we run it we have to add all the files we specified above. We have to put some code in the index.js and notes.js to test them.</p><p>Let us start with the index.js file first. Since it is our home or landing page all we are going to do is print “HOME PAGE” when the application runs. Open the index.js file in your text editor and use the following code:</p><pre>var express = require(&#39;express&#39;);<br>var router = express.Router();<br>router.get(&#39;/&#39;, function(req, res, next){<br>/* We are sending HOME PAGE message to the browser */<br>res.send(&#39;HOME PAGE&#39;);<br>});</pre><pre>/* exports is used in order to make this file available to other pages*/<br>module.exports = router;</pre><p>Save the file and open the notes.js file and do the same thing. We will print “NOTES PAGE” as our message to test it.</p><pre>var express = require(&#39;express&#39;);<br>var router = express.Router();</pre><pre>router.get(&#39;/notes&#39;, function(req, res, next){<br>res.send(&#39;NOTES PAGE&#39;);<br>});</pre><pre>module.exports = router;</pre><h3>Here is the full code of the app.js file putting together:</h3><pre>var express = require(&#39;express&#39;);<br>/* helps for file system path, it comes with the core */<br>var path = require(&#39;path&#39;);<br>/* body-parser accept data through a form and parse it to the DB */<br>var bodyParser = require(&#39;body-parser&#39;);<br>/* main app variable for express*/<br>var app = express();<br>/* port number to listen to */<br>var port = 4000;</pre><pre>/* create folders path */<br>/* we are creating two folders 1. index for our home page */<br>/* another one for or notes */<br>var index = require(&#39;./routes/index&#39;);<br>var notes = require(&#39;./routes/notes&#39;);</pre><pre>/* View Engine system will be used for the view in our app */<br>/* we are telling the system which folder to use for our views */<br>app.set(&#39;views&#39;, path.join(__dirname, &#39;views&#39;));<br>/* specify the engine to ejs */<br>app.set(&#39;view engine&#39;, &#39;ejs&#39;);<br>/* we are telling the system, to render html extensions */<br>app.engine(&#39;html&#39;, require(&#39;ejs&#39;).renderFile);</pre><pre>/* body parser middle ware, we are using the standard middle ware*/<br>/* we will be able to parse JSON */<br>app.use(bodyParser.json());<br>app.use(bodyParser.urlencoded({extended: false}));</pre><pre>/* this are the routes we are going to use */<br>/* the &#39;/&#39; is the landing page or the home page, it means root */<br>app.use(&#39;/&#39;, index);</pre><pre>/* we are using the &#39;/api&#39; for our notes route */<br>app.use(&#39;/api&#39;, notes);</pre><pre>/* listener to the port we specified which is 4000 */<br>/* if our port is correct and listens it will display &#39;Server started on 4000&#39; */<br>app.listen(port, function(){<br>/* checking if the server is running */<br>console.log(&#39;Server started on port &#39; + port);<br>});</pre><h3>Test the application</h3><p>Now we are done with our setup and it is time to test our application. In order to do that open the application folder in the command line. Make sure to access the folder before you run the application. To run our application use the following command:</p><pre>node app</pre><p>If you do everything correctly, you will see a message that said “Server started on port 4000” in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*nxv12JGunLqp2i87tcoWAA.png" /></figure><p>Now open your application in your browser. Type in “<a href="http://127.0.0.1:4000/">http://127.0.0.1:4000</a>” or “<a href="http://localhost:4000/">http://localhost:4000</a>” for our home page and <a href="http://localhost:4000/api/notes">http://localhost:4000/api/notes</a> or “http://localhost:4000/api/notes” for the notes page. You should see a messages “HOME PAGE” on the home page and “NOTES PAGE” on the notes page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*gib_7h-O7r5OQIk3URHCnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*Y25y1uCTw_ZagLERii2ecw.png" /></figure><p>But this is not what you want to achieve in real world application, but it is always the best way to test the routes before creating a real application. If we take the index.js file what we did with it is just print “HOME PAGE” using the send method “res.send(‘HOME PAGE’)”. What we need to do is use the EJS middleware to render an entire HTML file.</p><p>To render HTML file to our home page, we need to create an “index.html” file inside the views folder first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*vR42f2AzBKAeiwA3mhW5TA.png" /></figure><p>Now open the index.html file and add the following HTML code in it or create your own. I am going to put the same message “HOME PAGE” using the &lt;h1&gt; tag to test.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>   &lt;title&gt;Notes Manager&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>   &lt;h1&gt;Home Page&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Save the index.html file and open the index.js file inside the routes folder and update the code so it renders an HTML file instead of just printing message using send function. Replace the index.js file with the following code:</p><pre>var express = require(&#39;express&#39;);<br>var router = express.Router();</pre><pre>router.get(&#39;/&#39;, function(req, res, next){<br>/* We are rendering the index.html file we created to print ‘HOME PAGE’ message to the browser */<br>res.<strong>render</strong>(&#39;index.html&#39;);<br>});</pre><pre>/* exports is used in order to make this file available to other pages*/<br>module.exports = router;</pre><p>Now run node again. Please note each time you change something in the files, you need to <strong>restart</strong> the server in order to see the changes. To restart the server hold <strong>“control button”</strong> and press <strong>“c” </strong>and run the server again using “node app” command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*YGqtxbaPaysCaQc_HBjvZw.png" /></figure><p>Now refresh the home page on the browser if it is still open or type <a href="http://localhost:4000/">http://localhost:4000/</a> to test it. You should see a message saying “HOME PAGE”. So this is how you render an HTML page in node.</p><p>We now have successfully completed the application setup. The routes are working as expected. In the second part of the blog post we will be working on creating our MongoDB database using mLab.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2cda8117ccf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set up and run Node.JS for Beginners]]></title>
            <link>https://medium.com/@medan/how-to-set-up-and-run-node-js-for-beginners-a9473a25f6f6?source=rss-4a8efdfb08f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9473a25f6f6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Medhanie(Meda) Neguse]]></dc:creator>
            <pubDate>Wed, 21 Feb 2018 02:32:32 GMT</pubDate>
            <atom:updated>2018-02-27T00:52:09.757Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GABN89jti-utWXG0NHwlSQ.jpeg" /></figure><p>The following blog post is for those that are planning to start and setup their working environment for Node.js. In this blog, we will be covering the following four steps: first, installing Node.js, second adding your package.json file, third, how to setup your local host serve and finally I will show how you can run your first home (index.html) page using your local host. As I go through the steps, I will explain the steps and what each steps entails. Please note the focus of this tutorial is specifically for windows users.</p><p>I would like to mention to readers that this post is for complete beginners, so if you have previous experience in Node.js and have installed node in your local computer, this blog may not be appropriate for you.</p><h4>Installing Node to your computer</h4><p>Installing Node is very straight forward. All you have to do is go to the Node.js website <a href="https://nodejs.org/en/">here</a><strong> </strong>and download the recommended version for windows. If you are using Mac follow the instruction <a href="https://treehouse.github.io/installation-guides/mac/node-mac.html">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtKqfQpPkMTKhdn-7ok0DA.png" /></figure><p>Once the download is complete, run or install the downloaded file by double clicking on the file, or right click on the file and click install. After doing so, you will see the Node.js installation wizard. The default installation is always recommended so click next without changing anything and finish the installation. Once the installation is complete, you will see a folder called nodejs inside you program files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*EShfmNgrFftTsp_b2O7NGA.png" /></figure><p>Now open the folder and you will see a file with a name “node.exe”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*dOf2o58o83JmuuGgcRPyNw.png" /></figure><h4>Run Node</h4><p>You can run Node in two ways from your computer. The first one using the node.exe inside the nodejs folder in your program files. The second method is using the command line.</p><p>To run Node using node.exe file, double clicking on it or do right click on the file and hit open. This will open and run Node. You can test the node shell by typing a JavaScript code on it. I tested mine math operation and by calling the date method see the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*kFY-lLnJYJDChpwGWJoh-A.png" /></figure><p>Now let’s try to run node from the <strong>command line</strong>. To use the command line go to your program by clicking on start and open the command Prompt. Once the command line opens type in “node” and hit enter on your keyboard. This will run node automatically. Please notice the change of the directory on the command line, it will change to a “&gt;” sign. As we did earlier you can test if node is running by typing JavaScript codes as we did above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*zOcau5MplISYSOS6uU0LUQ.png" /></figure><p>Now that we know that Node is installed and runs as expected we have completed the first step successfully. Let us move to the next step of the tutorial which is creating the package.json file.</p><h4>Creating package.jason file</h4><p>Packages.json file is the best way to manage locally installed npm packages. These packages are the ones that your application is going to depend on. Moreover, your build will be easy to be copied by other developers if you wish to share them.</p><p>A package.json file must have a name of the application and the version of the application, without them our package won’t be installed. Also the name must be all lowercases and one word with no spaces, with the exception of dashes and underscores between words. The version on the other hand should follow the semantic versioning rules and it have to be in “<strong>x.x.x</strong>“ form. If you want to read about the semantic versioning in more detail, please <a href="https://docs.npmjs.com/getting-started/semantic-versioning">click here</a>.</p><p>For example here is apaskage.json file with the required fields name and a version specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*x6WNfc3UCocLv27aKqUhNQ.png" /></figure><p>In our application, we can create packages.json file using two methods. The first one is using the default process method and the second one is using the CLI questionnaire method.</p><p>To get the default package.json file, we run the “<strong>npm init</strong>” with the — yes or -y flag: by using this code we install our package.json file with the default setup.</p><pre>npm init — yes</pre><p>To create the package.json file using the CLI (Command Line Interface) questionnaire that allow us to supply our own values we use:</p><pre>npm init</pre><p>For this tutorial we will use “npm init”.</p><p>Let us create our own package.json file now, but before we do we have to create a folder for our application. I will create a folder called “myApp” inside my “C” drive. You can create the folder anywhere you want as long as you remember the file path. After creating the folder, open your command prompt and change the directory to the folder you created. To do that type “cd &lt;Folder Path&gt;” and hit enter. Ex: mine will be “cd C:/myApp” The path will change to the location of the folder you created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*mAdjAiN0u_9Rc7gWjzqUCg.png" /></figure><p>Now type in the code specified above. I am going to use “npm init” to create the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*1IsobA091rHSEpf05QRzDA.png" /></figure><p>After typing, hit enter and you will be prompt to add values to the package.json file. Please note that if you leave the values to the name, as well as leave the Package Name and version, the values in bracket will be added by default. I will give values to the name, main and author only. I will leave the version to its default which is 1.0.0.</p><p><strong>name</strong>: mysimpleapp</p><p><strong>version</strong>: leave as default which is 1.0.0</p><p><strong>description</strong>: empty</p><p><strong>main</strong>: app.js</p><p><strong>scripts</strong>: empty</p><p><strong>keywords</strong>: empty</p><p><strong>author</strong>: empty</p><p><strong>license</strong>: <a href="https://opensource.org/licenses/ISC">ISC</a></p><p>After filling the information you need, hit enter to confirm that it is okay to create the package.json file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*NRQouLJg4zLpmKN6US-bdw.png" /></figure><p>Now check inside the folder you created. You will see a package.json file that you created above. If you open the file you will see the information you specified in it. You can open the file using a test editor for code or you can use Notepad.</p><p>The purpose of package.json file is to manage the modules we use in our applications, they are also known as dependencies. Dependencies are modules that our application depends on. For example, if we want to use Express in our application we install Express from node package manager(npm). When we install Express, our package.json file will be updated and put express under dependencies. In the figure below application foo has three dependencies express, mocha and modules. These are modules the foo application depends on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*Fg1li3P94EvTqPgFqYKXTw.png" /></figure><p>We are not going to install any modules for this tutorial, but you can try it to see for yourself. For more information on packages please <a href="https://docs.npmjs.com/getting-started/using-a-package.json">click here</a>.</p><h4>Server</h4><p>Now that we have created the package.json file, it is time to set up our server. We are going to use the app.js file we specify on the entry point during the package.json file creation. Inside the folder of our application create a new file called “app.js”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*WWjl91ALO8bCVlhQtXbtXA.png" /></figure><p>Now open the file inside your text editor. I am using Sublime(https://www.sublimetext.com/) text editor, but you can use Notepad++, Notepad, or any other digital writing software to your liking. Once you open the app.js file copy the code below and paste it inside app.js file and save it. The code is from Node.js website you can find it <a href="https://nodejs.org/en/about/">here</a>.</p><pre>// this is how you import a module in Node. In the code bellow<br>// we are importing the &#39;http&#39; module and storing it into the http //variable<br>const http = require(&#39;http&#39;);</pre><pre>// The code 127.0.0.1 is a loopback or it is called localhost<br>const hostname = &#39;127.0.0.1&#39;;</pre><pre>// we are seting a port varable that holds 3000 as our port<br>const port = 3000;</pre><pre>//the code below will create a server by using the http object and //createServer method<br>//req == request<br>//res == response<br>const server = http.createServer((req, res) =&gt; {<br>//res,ststusCode is 200 meaning if everuthig is OKAY<br>res.statusCode = 200;<br>//the setHeader is here to tell the browser what kind of file we are //passing on, the content type we are passing a plain text<br>res.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;);</pre><pre>//the code below is the one that will be printed on the browser. It //will print Hello World when the page loads<br>res.end(&#39;Hello World\n&#39;);<br>});</pre><pre>//the code below is here to listen on the server using the hostname //and port we specified above our port is 3000<br>// our hostname is 127.0.0.1 or localhost<br>server.listen(port, hostname, () =&gt; {<br>console.log(`Server running at http://${hostname}:${port}/`);</pre><pre>});</pre><p>If you are not sure what the code does, I have put a comment explaining what each line of code and method does.</p><p>Now we can open the command line and run the app.js file using node and it will create us a localhost server that we can use to run and test our application in the browser. To run the app.js file we created using the command line type in “node app” and hit enter. If you do everything correctly, you should see a message in the command line “Server running at <a href="http://127.0.0.1:3000/">http://127.0.0.1:3000/</a>”. See image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*-yx0hsDxBpEgc-XkT5pbaQ.png" /></figure><p>To test if our application is running in the localhost, open any browser and type in “<a href="http://127.0.0.1:3000/">http://127.0.0.1:3000/</a>” or “http://localhost:3000/”, you should see a text “Hello World” in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*zZb7yk1WcMG5DY1-d2eCxQ.png" /></figure><p>What we have now is just a server that says “Hello world”. In the feature when you build your application, this will be the place you see the changes. You can set your port to your desired port number Ex: 8000 and it will run in port 8000.</p><p>Now let see change the app.js file so it can run a template that we create. The template we are going to run is for our home or index page. To create our index template, let us create a index.html file inside our folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*4-_S0P9zeM5LW-f68EJAsQ.png" /></figure><p>Now open the index.html on your text editor and use this html code below or create your own if you are familiar with html programming.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br> &lt;title&gt;My First App&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;My Home Page.&lt;/h1&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>In order to run the index.html file we need to do some changes in our app.js file, we have to tell our app to read the index.html file instead of printing “Hello World”. To do that we have to use the code below, so open your app.js file and replace it with the code below and save it.</p><pre>const http = require(&#39;http&#39;);</pre><pre>// we added the code below to read files that we created. fs stands // for file system. We import the file system to our application so // we can read the index.html file we created<br>const fs = require(&#39;fs&#39;);</pre><pre>const hostname = &#39;127.0.0.1&#39;;<br>const port = 3000;</pre><pre>// we are reading the index.html file we created by using the file // system object readFile method is used to read the index file<br>// we have two methods inside readFile mthod. error and html</pre><pre>fs.readFile(&#39;index.html&#39;, function(error, html){</pre><pre>// we are checking if there is an error reading out index.html file // we are telling it to throw the error instead of crashing<br> if (error){<br>  throw error;<br> } else {  <br>// if there is no problem reading our index.html file we create our // server and write to our home page<br>  const server = http.createServer((req, res) =&gt; {<br>    res.statusCode = 200;<br>// we change the Content-type in here to texr/html - because we are // reading a html file (index.html)<br>    res.setHeader(&#39;Content-Type&#39;, &#39;text/html&#39;);<br>    //we are writing the html file to the browser<br>    res.write(html);<br>    res.end();<br>  });<br>  <br>  server.listen(port, hostname, () =&gt; {<br>    console.log(`Server running at <a href="http://${hostname}:${port}/`">http://${hostname}:${port}/`</a>);<br>  });<br> }<br>});</pre><p>The only changes we made from the previous code is very minimum, but the setup is a little bit different since we are reading a file (index.html). I have commented on top of the code above to help you understand what we did.</p><p>If you run the server again it will read the index.html file we created and print “My Home Page” in the browser. If you did not see the change, you have to run the server again. In order to run the server again go to the command line, hold the control button and click “c“ this will exit and stop the server from running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*9H0Q828yc4RbU_i4hqYFRg.png" /></figure><p>Now run it again, by typing “node app” again. This will refresh the server and will show you the changes we made. You can check the server in your browser “<a href="http://127.0.0.1:3000/">http://127.0.0.1:3000/</a>” or <a href="http://localhost:3000/">http://localhost:3000/</a> to see the changes. You should see “My Home Page” see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*o9zky9Vb7NK5LlQXwGmiCQ.png" /></figure><p>Hopefully, you like my post and learned something from my tutorial. This post is just a basic explanation on how to setup your node environment and run a very simple server in Node.js using a code provided in node documentations. In my next blog post, I will try to give you something useful and a little bit more advanced material. If you need to learn more about the codes above please see the documentation in Node.js.</p><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9473a25f6f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s guide to Node.js]]></title>
            <link>https://medium.com/@medan/beginners-guide-to-node-js-f724dceb0e91?source=rss-4a8efdfb08f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f724dceb0e91</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Medhanie(Meda) Neguse]]></dc:creator>
            <pubDate>Tue, 23 Jan 2018 01:42:14 GMT</pubDate>
            <atom:updated>2018-01-23T01:42:14.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GABN89jti-utWXG0NHwlSQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ilyapavlov">I<strong>lya Pavlov</strong></a><strong> on </strong><a href="https://unsplash.com/"><strong>Unsplash</strong></a></figcaption></figure><p>If you are planning to learn a new language within the IT industry, develop an application, or require some information on Node.JS you are in the right place. This blog post is for people that require a brief and easily digestible information about Node.js. I hope the blog post will provide you with enough exposure which will ultimately guide you in the right direction.</p><h3>What is Node.js?</h3><p>Node.js is a JavaScript runtime on chrome’s V8 JavaScript engine. The program V8 is written in C++ and the browser chrome is built with it.</p><p>We all know that JavaScript was mainly used for front-end or client side development in the past years. But now we can use JavaScript on the server using Node.js to build powerful, fast and scalable web application.</p><p>One of the main reasons for Node.js popularity is its ability to use an event-driven, non-blocking I/O mode. You probably are confused about the technical jargons, but let’s translate them to something we all can understand.</p><p>If you are familiar with traditional server side technologies like PHP and Apache, each connection or request creates a new thread. This means if we have ten requests, it will create ten threads for each of the connections. One thing we need to understand here is that when the threads created it does not mean that all of them will be executed at the same time they have to wait for their specific turn in line until the first one is completed and the order continues. So until the execution happens it has to wait in the system memory. This kind of process is memory intensive and the process of waiting one task to finish before starting a new one is called a synchronous way.</p><p>On the other hand, Node.js works in asynchronous. It can execute multiple tasks at the same time. Node.js works in a single thread and uses a non-blocking I/O module which allows it to support thousands of connection concurrently that are held in the event loops. In another word, one task does not have to wait for another task to finish in order to be executed, this process is not CPU intensive, because none of the tasks are not waiting in line to be executed so there is nothing to store inside the system memory.</p><p>Similarly, when we say Node.js is an event-drive system, it all means is that it only reacts when an event occurs on the server. It uses <strong>eventEmitter</strong> class to bind events to listeners in the application. Whenever a new event is detected, the trigger will call back the new events detected synchronously without blocking. This allows us to create high performance, highly scalable, “real-time” applications.</p><h3>NPM</h3><p>NPM (Node.js package manager) helps JavaScript developers to share codes they have written to solve a particular problem, as well as for other developers it helps them to reuse codes of other developers. In another words it is used to install packages, also known as modules.</p><p>NPM is one of the largest software registries with over half a million JavaScript codes available to be downloaded by developers around the world. Since every developer solves his or hers problems, the codes are mainly relevant to solve one specific problem. This will allow other developers to reuse the code instead of creating a new one if it relates to their problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tuhot5FG0i3j-jQTPIhmaA.png" /></figure><p>Not only does NPM helps to reuse codes of other developers, but it also helps developers to work together to obtain better results by learning from others with diverse expertise. Most packages or modules inside NPM can be used for server side, command line, and front end.</p><p>Another aspect of Node.js is that it includes three types of modules: 1) core modules, 2) local modules, and 3) third party modules. The <a href="https://nodejs.org/api/modules.html#modules_core_modules">core modules</a> are compiled in the binary distribution and they load automatically when Node.js starts. They reside inside the lib/ folder.</p><p>NPM comes as part of the core modules, so we are not required to install it. However, when we use any of the modules we have to import it by requiring it on top of our application.</p><pre>var module = require(‘module_name’);</pre><p>For example <strong>http </strong>is one of the modules that in the core module, in order to use it we have to require it first. The figure below demonstrates how importing from the core is required to utilize the module.</p><pre>const http = require(&#39;http&#39;);</pre><pre>const server = http.createServer((req, res) =&gt; {</pre><pre>res.statusCode = 200;</pre><pre>res.setHeader(&#39;Content-Type&#39;, &#39;text/plain&#39;);</pre><pre>res.end(&#39;Hello World\n&#39;);</pre><pre>});</pre><p>To use modules from NPM simply go to the NPM website and look for the module or the problem you want to solve by searching through the available packages. For example, if you need user a weather app in your application, simply type in weather or use the advance filter search method and search for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eRr-rfgeaMWN-JWLLkoQaQ.png" /></figure><p>After you click search you will be directed to a list of weather related modules that are written by a developers around the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLBVhWVJasi6XMYkWXXOdg.png" /></figure><p>For our search “weather”, we instantly get 720 packages, though this obviously an overwhelming number of results; we can use the filter on the left to refine our search.</p><p>After going through the results of your search, select a package that you want and read the documentation on how to use it in your application. All of the packages in NPM comes with documentations on how to install the package and information about the package. If you open one of the packages from your search, it will show you description of the module, instruction of installation, the amount of downloads by users, any issue on the module that are reported.</p><h3>Documentation</h3><p>When developing any type of application, we tend to depend on the information from the host or online. But, one thing to consider when reading or copying codes is its stability. This question always lingers within a programmer’s mind, before using any code in to his/hers application. It seems like people from Node.js have solved this issue. One of the benefits of using the documentation in Node.js website is that it lets you see the stability level of the code you are about to use. These <a href="https://nodejs.org/api/documentation.html#documentation_stability_index">stability levels</a> are color coded and presented under the title inside the documentations. The color codes are red, green, and orange. Red stands for stability 0, orange for stability 1, and green for stability 2. See the figure below for description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQcV5hVZvgSBFdDLpra-Cw.png" /></figure><p>For instance if you need to use the HTTP server and client interface <a href="https://nodejs.org/api/http.html">here</a>, it will give you all the information you need and show you the stability level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*XoDBfm3fj5yt-ZpfULZJig.png" /></figure><p>Besides the website documentations, Node.js has repository in GitHub to help users, if you need help <a href="https://github.com/nodejs/help/issues">click here</a>. For issue and info on resolving the issues in Node.js click <a href="https://github.com/nodejs/node/issues">here</a>.</p><p>As mentioned above, Node.js is one of the best JavaScript runtime platforms that allows you build fast, scalable network applications easily. Whether you want to use node for REST APIs and back-end, real-Time Services like chats and game, blogs, content management systems, and utilities in general anything that is not CPU–intensive, Node.js is the best framework to work with. For more information <a href="https://nodejs.org/en/">read more here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f724dceb0e91" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>