<?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 Robert Tod on Medium]]></title>
        <description><![CDATA[Stories by Robert Tod on Medium]]></description>
        <link>https://medium.com/@roberttod?source=rss-e66d0c67becc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YQ1ktaXFGVqYEkun8K-Ezg.jpeg</url>
            <title>Stories by Robert Tod on Medium</title>
            <link>https://medium.com/@roberttod?source=rss-e66d0c67becc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:17:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roberttod/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[Automatically start your dev server on VS Code project open]]></title>
            <link>https://medium.com/@roberttod/automatically-starting-dev-server-on-vs-code-project-open-d79284dc5064?source=rss-e66d0c67becc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d79284dc5064</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Robert Tod]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 05:55:55 GMT</pubDate>
            <atom:updated>2023-02-24T06:22:08.813Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I was working and noticed how long it takes to start a dev server or bundler whenever I open a project. You may need to read through the readme, or run through scripts in package.json to find the right one. I decided to write a little script to run a command automatically when opening a project in vscode.</p><p>Below I will describe how to set this up all by yourself using just your .bash_profile or .bashrc file.</p><p>First, let’s write our .vscoderc file in a project (this filename is not recognized by vscode as far as I am aware, we are using this name to run the file in your .bash_profile).</p><p><em>You may want to add this file to the .gitignore if others on your team aren’t also using this method of auto running servers/starting projects.</em></p><pre># .vscoderc at the root of your project<br><br># manually set this to match the port of your app or<br># you can customize it to read port from a config<br># curl --silent --output /dev/null localhost:&lt;app_port&gt; || your-run-command<br>curl --silent --output /dev/null localhost:3000 || npm run dev<br><br># if nothing on port then dev will now run<br># unfortunately the curl command is a bit noisy even on silent<br># so when opening new VSCode terminal tabs, expect a bit of<br># text when this bit gets run.</pre><p>This works for all kinds of servers, just use whatever your server uses to start e.g. `go run server.go` for a go project.</p><p><em>This can also be used for starting a frontend packaging server such as webpack, just specify it in your .vscoderc start command.</em></p><p>Now, let’s run it from your .bash_profile (or from now on .bashrc or equivelent if you are on Linux and don’t have a .bash_profile).</p><pre># open your ~/.bash_profile<br>code ~/.bash_profile</pre><p>Then add the following commands to run .vscoderc if it detects VS code is running it</p><pre># ~/.bash_profile file<br><br># commnad for <br># if TERM_PROGRAM=vscode then run &quot;npm run dev&quot; in vscode terminal<br>if [ &quot;$TERM_PROGRAM&quot; = &quot;vscode&quot; ]; then<br>    source .vscoderc<br>fi<br><br>source<br></pre><p>That’s it! From now on you can add a .vscoderc to any project and it will run start it up for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iue1Tpqjp0r6MsN6wU5XHQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d79284dc5064" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing MySQL on Mac]]></title>
            <link>https://medium.com/@roberttod/installing-mysql-on-mac-88d39eea8bfd?source=rss-e66d0c67becc------2</link>
            <guid isPermaLink="false">https://medium.com/p/88d39eea8bfd</guid>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[homebrew]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Robert Tod]]></dc:creator>
            <pubDate>Thu, 18 May 2017 20:04:21 GMT</pubDate>
            <atom:updated>2017-05-18T20:04:21.821Z</atom:updated>
            <content:encoded><![CDATA[<p>This short tutorial shows how to install MySQL on a Mac using Homebrew and how to verify it is running using Sequel Pro.</p><h3>Install Homebrew</h3><p><a href="https://brew.sh/">Homebrew</a> is a package manager for Mac and serves a similar purpose to apt-get in Linux.</p><p>If you already have Homebrew, you can skip this section. If you are not sure, run the following command.</p><pre>which brew</pre><p>If you have Homebrew it will print something similar to /usr/local/bin/brew. If you do not have Homebrew it will print nothing.</p><p>Run the following command in a terminal window to install Homebrew.</p><pre>/usr/bin/ruby -e &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)&quot;</pre><h3>Install MySQL</h3><p>Update Homebrew to ensure you get the latest packages</p><pre>brew update</pre><p>Run this command to install MySQL</p><pre>brew install mysql</pre><p>You will want to keep MySQL running whenever your computer is started. To do this, use brew to start the MySQL daemon.</p><pre>brew services start mysql</pre><p>Set a rudimentary password for MySQL locally, there is no need to worry about security because it will only be accessible from your machine (I used “password”).</p><pre>mysqladmin -u root password &#39;password&#39;</pre><p>Once installed and running, MySQL is accessible to any app running locally on your machine.</p><h3>Verify MySQL is running</h3><p>I use <a href="https://www.sequelpro.com/">Sequel Pro</a> to manage MySQL because it has a pretty great UI. In case you are wondering, I am not actually affiliated with it in anyway.</p><p><a href="https://sequelpro.com/download#auto-start">Download and install Sequel Pro</a> and open it. The database to connect to is on localhost so set “host” to “127.0.0.1”. Username is “root” and password the same as chosen in the previous step, for me that’s “password”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wSgaDmauCW4WSJ2ekJnpbw.png" /></figure><p>Connect and you will be presented with an empty MySQL. If the connection does not work, make sure you modified your password correctly in the previous step and that the mysql service is still running.</p><p>At this point, you might want to add your first database. After successfully connecting, click Database &gt; Add Database and name it, I chose the name “tutorial_node_database” (the MySQL naming convention is snake_case).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBYxsLrginQkguoE7FRTjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*jzV_YdeszInbgQl-Ht5U7Q.png" /></figure><p>MySQL is ready to go!</p><p>If you are interested in using MySQL with Node.js, check out the <a href="https://hackernoon.com/setting-up-node-js-with-a-database-part-1-3f2461bdd77f">setting up Node.js with a database</a> tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88d39eea8bfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install Node.js (mac/linux)]]></title>
            <link>https://medium.com/@roberttod/how-to-install-node-js-mac-linux-9c5304494e59?source=rss-e66d0c67becc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c5304494e59</guid>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Robert Tod]]></dc:creator>
            <pubDate>Thu, 18 May 2017 19:40:15 GMT</pubDate>
            <atom:updated>2020-02-01T02:59:34.933Z</atom:updated>
            <content:encoded><![CDATA[<p>This short tutorial shows how to install <a href="https://github.com/creationix/nvm">NVM</a> (Node version manager) and the latest version of Node. It’s good to use NVM to manage node so that new versions can be easily installed and you can switch between different versions.</p><p>Before installing NVM make sure you have a .bashrc file in your home directory (even if the file is empty).</p><pre>touch ~/.bashrc</pre><p>To install NVM just run this command (<a href="https://github.com/creationix/nvm">as written in the NVM installation instructions</a>).</p><pre>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash</pre><p>This command pulls down a script from a remote URL and runs it.</p><p>You now have NVM! But if you run nvm ls you will notice it isn’t found. This is because NVM adds some code to your ~/.bashrc. This file is a special file that is run every time you log in to your instance, so to get NVM running you could logout and login again. However you can just run the file manually by using the source command.</p><pre>source ~/.bashrc</pre><p>Now running nvm ls works! But there aren’t any node versions installed! To get the latest version, just nvm install &lt;latest version number&gt;.</p><pre>nvm install 12</pre><p>You have node installed! Check that it’s there by looking at the version</p><pre>node --version</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c5304494e59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Setting up Node.js with a database]]></title>
            <link>https://medium.com/hackernoon/setting-up-node-js-with-a-database-part-1-3f2461bdd77f?source=rss-e66d0c67becc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f2461bdd77f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Robert Tod]]></dc:creator>
            <pubDate>Sun, 07 May 2017 21:47:47 GMT</pubDate>
            <atom:updated>2019-04-09T18:16:59.172Z</atom:updated>
            <content:encoded><![CDATA[<p>I could have named this tutorial “setting up Node.js with MySQL” however I wanted to make the name a little more encompassing because I think for most applications MySQL is a great choice for Node.js.</p><p>MySQL has been around for 21 years and so in early Node.js apps it was often overlooked for some new and shiny NoSQL choices such as MongoDB. However with the benefit of hindsight, MongoDB turned out to be more hype than substance and is well known for a few major security issues and performance issues. If you don’t believe me, <a href="https://hn.algolia.com/?query=mongodb&amp;sort=byPopularity&amp;prefix&amp;page=0&amp;dateRange=all&amp;type=story">search Hacker News for “mongodb”</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5rN4F-qhr1-x4FD9jSLqg.png" /></figure><p>If you would like a DB, <a href="http://blog.wix.engineering/2015/12/10/scaling-to-100m-mysql-is-a-better-nosql/">even for NoSQL</a>, MySQL is a great choice. It has great support, decent performance and there are some great NPM modules for interfacing with it. Furthermore there are MySQL adapters for pretty much everything.</p><p>In this tutorial, I will show how to setup MySQL with Node using <a href="http://knexjs.org/">Knex</a> in order to create a crude app for creating and logging in users.</p><p>We will</p><ul><li>Install Node.js</li><li>Install MySQL</li><li>Create a HTTP API for writing to the database</li><li>Create some HTML and JS to POST to the API</li><li>Use Knex migrations to create a user database schema (a similar process to Rails migrations)</li><li>Use a migration to setup password hashing</li><li>Create a login route to check the hashing works</li></ul><p>In the next tutorial we will add more functionality to the app and explore some more complex querying. Eventually we will deploy the app somewhere.</p><h3>Installing Node.js</h3><p>If you have completed the previous tutorials, you probably have Node installed so you can skip this section.</p><p>We will be using NVM to manage node so that we can easily install and switch between different versions.</p><p>Before installing NVM make sure you have a .bashrc file in your home directory (even if the file is empty).</p><pre>touch ~/.bashrc</pre><p>To install NVM just run this command (same as in the NVM installation instructions).</p><pre>curl -o- <a href="https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh">https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh</a> | bash</pre><p>This command pulls down a script from a remote URL and runs it.</p><p>You now have NVM! But if you run nvm ls you will notice it isn’t found. This is because NVM adds some code to your ~/.bashrc. This file is a special file that is run every time you log in to your instance, so to get NVM running you could logout and login again. However you can just run the file manually by using the source command.</p><pre>source ~/.bashrc</pre><p>Now running nvm ls works! But there aren’t any node versions installed! To get the latest version, just nvm install &lt;latest version number&gt;.</p><pre>nvm install 7</pre><p>You have node installed! Check that it’s there by looking at the version</p><pre>node --version</pre><h3>Installing MySQL</h3><p>If you are using Mac, you should install MySQL using <a href="http://brew.sh/">Homebrew</a>. If you are using another platform just Google something like “installing MySQL on my platform” for instructions.</p><p>Install Homebrew on mac by running this in terminal</p><pre>/usr/bin/ruby -e &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)&quot;</pre><p>Once installed, update Homebrew and install MySQL</p><pre>brew update<br>brew install mysql</pre><p>Run the MySQL daemon</p><pre>brew services start mysql</pre><p>Set a rudimentary password for MySQL locally, there is no need to worry about security because it will only be accessible from your machine (I used “password”).</p><pre>mysqladmin -u root password &#39;password&#39;</pre><p>Once installed and running, MySQL is accessible to any app running locally on your machine.</p><p>In this tutorial, we will use <a href="https://www.sequelpro.com/">Sequel Pro</a> to manage our database. <a href="https://sequelpro.com/download#auto-start">Download and install Sequel Pro</a> and open it. The database to connect to is on localhost so set “host” to “127.0.0.1”. Username is “root” and password the same as chosen in the previous step, for me that’s “password”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wSgaDmauCW4WSJ2ekJnpbw.png" /></figure><p>Connect and you will be presented with an empty MySQL. If the connection does not work, make sure you modified your password correctly in the previous step and that the mysql service is still running.</p><p>After successfully connecting, click Database &gt; Add Database and name it, I chose the name “tutorial_node_database” (the MySQL naming convention is snake_case).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBYxsLrginQkguoE7FRTjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*jzV_YdeszInbgQl-Ht5U7Q.png" /></figure><p>Great, MySQL is ready to go!</p><h3>Project setup</h3><p>I have added this whole project to <a href="https://github.com/roberttod/tutorial-node-database">a public github repo</a> and I have broken down each step as a commit so it should be easy to follow. This is just as an aid, we will be creating the project from scratch so there is no need to clone the code.</p><p>Let’s start with a fresh directory, I have named the project tutorial-node-database. Run the following to create the file structure.</p><pre>mkdir tutorial-node-database<br>cd tutorial-node-database</pre><pre>touch knexfile.js<br>touch index.js<br>touch store.js</pre><pre>mkdir public<br>touch public/index.html<br>touch public/app.js</pre><pre># choose all defaults when prompted<br>npm init</pre><p>We are using Knex with MySQL and creating a small API using express, so you need to install knex and express. We’ll also use the body-parser module.</p><pre>npm i knex mysql express body-parser --save</pre><p>knex should be installed globally also</p><pre>npm i knex -g</pre><p>When creating a new project I like to add a minimal .gitignore file so that I can easily check everything in without including the node_modules folder or .DS_Store files that MacOS likes to create.</p><pre>printf &quot;node_modules\n.DS_Store&quot; &gt; .gitignore</pre><p>Don’t worry if you don’t understand the bash code above. All it does is put node_modules followed by a newline \n followed by .DS_Store into a file called .gitignore. It’s perfectly reasonable to use an editor to do this sort of thing if that’s more simple for you.</p><h3>HTTP API</h3><p>We’ll start with a simple express app, serving the public directory, with a /createUser endpoint to write some data to the database.</p><pre>const express = require(&#39;express&#39;)<br>const bodyParser = require(&#39;body-parser&#39;)</pre><pre>const store = require(&#39;./store&#39;)</pre><pre>const app = express()<br>app.use(express.static(&#39;public&#39;))<br>app.use(bodyParser.json())<br>app.post(&#39;/createUser&#39;, (req, res) =&gt; {<br>  store<br>    .createUser({<br>      username: req.body.username,<br>      password: req.body.password<br>    })<br>    .then(() =&gt; res.sendStatus(200))<br>})</pre><pre>app.listen(7555, () =&gt; {<br>  console.log(&#39;Server running on <a href="http://localhost:7555&#39;)">http://localhost:7555&#39;)</a><br>})</pre><p>Save this to index.js. When we run this file, the server will listen on <a href="http://localhost:7555&#39;)">http://localhost:7555</a> for POST requests to /createUser and pass those requests to the store file. The server will then respond with a 200 status code (200 is the code that every HTTP server uses to say that the request was successful).</p><p>For the time being, we will mock the store in order to check that our API works.</p><pre>module.exports = {<br>  createUser ({ username, password }) {<br>    console.log(`Add user ${username} with password ${password}`)<br>    return Promise.resolve()<br>  }<br>}</pre><p>Save this to store.js. Note that the addLog function returns a promise so that you know when it is done. If the use of promises here is a little confusing, it might be worth checking out some Promise tutorials, they are an essential concept in modern Javascript.</p><p>Now, lets write a simple index.html, including app.js. We add app.js at the bottom of the HTML here rather than the head so that we can easily query elements above the script, without needing to use something like jQuery.ready or the DOMContentLoaded event to wait for them to load.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Node database tutorial&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;form class=&quot;CreateUser&quot;&gt;<br>    &lt;h1&gt;Create a new user&lt;/h1&gt;<br>    &lt;input type=&quot;text&quot; class=&quot;username&quot; placeholder=&quot;username&quot;&gt;<br>    &lt;input type=&quot;password&quot; class=&quot;password&quot; placeholder=&quot;password&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Create user&quot;&gt;<br>  &lt;/form&gt;<br>  &lt;script src=&quot;/app.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The app.js script should look like the below and will be used to hit the server’s /createUser endpoint.</p><pre>const CreateUser = document.querySelector(&#39;.CreateUser&#39;)<br>CreateUser.addEventListener(&#39;submit&#39;, (e) =&gt; {<br>  e.preventDefault()<br>  const username = CreateUser.querySelector(&#39;.username&#39;).value<br>  const password = CreateUser.querySelector(&#39;.password&#39;).value<br>  post(&#39;/createUser&#39;, { username, password })<br>})</pre><pre>function post (path, data) {<br>  return window.fetch(path, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Accept&#39;: &#39;application/json&#39;,<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    },<br>    body: JSON.stringify(data)<br>  })<br>}</pre><p>Save this to public/app.js and start your server.</p><pre>node .</pre><p>Your server should start on <a href="http://localhost:7555/">http://localhost:7555/</a>. Go to this link and you will be able to see createUser requests in the network panel when you click “Create User”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4sJEHR_9AywUFbhcgF_UA.png" /></figure><p>Check your terminal for the console.log from store.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*JV49x8TQMPGDXEIAAEnvyA.png" /></figure><p>This is a good point to commit your code if you are using git.</p><pre># An empty first commit is nice<br>git commit --allow-empty -m &quot;( ͡° ͜ʖ ͡°)&quot;</pre><pre>git add .<br>git commit -m &quot;Setup server with mock store&quot;</pre><h3>Setting up knex</h3><p>Let’s set up the knexfile.js to connect to the database.</p><pre>module.exports = {<br>  client: &#39;mysql&#39;,<br>  connection: {<br>    user: &#39;root&#39;,<br>    password: &#39;password&#39;,<br>    database: &#39;tutorial_node_database&#39;<br>  }<br>}</pre><p>I have used default credentials to connect locally to MySQL, you may need to change this if yours are different.</p><p>For the tutorial we will need a user table with a username and password. These all need to be defined in schema. To create or modify schemas, we will use Knex migrations.</p><p>Create a new migration and name it something meaningful</p><pre>knex migrate:make create_user_table</pre><p>This will create a file like migrations/20170504155313_create_user_table.js. The name of the file is the current datetime followed by the name you specified. The datetime keeps the migration files in order in the filesystem, making them easy for you to read in chronological order.</p><p>Every time we need to add, remove or modify a table or column in order to change how our data will be represented, we’ll write a new migration file. This allows us to</p><ul><li>Make schema changes programmatically that can be checked into git and reviewed (far better than updating schema using MySQL directly)</li><li>Create a history of schema updates</li><li>Use JS rather than SQL to transform values (with the ability to use NPM modules and functions internal to the project)</li><li>Keep all the project collaborators’ database schema up to date, they can run the latest migrations to get the latest changes</li><li>Update staging and production databases when deploying code changes</li><li>Rollback schema changes</li></ul><p>The created file contains code which exports an up method and down method. We will create our table schema in the down method (used when we migrate) and delete it in the up method (when we roll back).</p><pre>exports.up = function (knex) {<br>  return knex.schema.createTable(&#39;user&#39;, function (t) {<br>    t.increments(&#39;id&#39;).primary()<br>    t.string(&#39;username&#39;).notNullable()<br>    t.string(&#39;password&#39;).notNullable()<br>    t.timestamps(false, true)<br>  })<br>}</pre><pre>exports.down = function (knex) {<br>  return knex.schema.dropTableIfExists(&#39;user&#39;)<br>}</pre><p>The API for Knex is pretty straightforward and the <a href="http://knexjs.org/">docs are very simple to read</a>. It is important to realize that Knex is actually constructing SQL from the calls you make. Although you are using a JavaScript API, a lot of queries are built with the underlying SQL in mind which can be very important when it comes to query performance and optimization.</p><p>Note that we add an id fields here that will automatically increment as well as updated_at and created_at fields using the t.timestamps method.</p><p>To run this migration</p><pre>knex migrate:latest</pre><p>Check SequelPro to see the new table with the schema specified</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEmp2G3YHUBMQ3YFUZ6qcQ.png" /></figure><p>Now we have a table, we can edit store.js so that it writes data to the table.</p><h3>Using Knex.js to write data</h3><p>All we need our store to do is load in knex using the knexfile.js config and then write data to the user table whenever a createUser request is made.</p><pre>const knex = require(&#39;knex&#39;)(require(&#39;./knexfile&#39;))</pre><pre>module.exports = {<br>  createUser ({ username, password }) {<br>    console.log(`Add user ${username} with password ${password}`)<br>    return knex(&#39;user&#39;).insert({<br>      username,<br>      password<br>    })<br>  }<br>}</pre><p>Restart your server and browse to <a href="http://localhost:7555/">http://localhost:7555/</a> to create a user. If you go to Sequel Pro you should see the new user show up in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBtzF7kDmGMOnEfplM2tXw.png" /></figure><pre>git add .<br>git commit -m &quot;Setup knex&quot;</pre><h3>Storing the password safely</h3><p>Let’s make sure the password is encrypted in the DB before going any further. The flexibility of using database migrations really comes in handy.</p><p>To safely store passwords, you want to create a random salt for each new user and use crypto to encrypt the password (this is standard practice and safeguards against leaking your user’s passwords if your database is compromised).</p><p>Before the migration, let’s add the encryption logic into the store.js file</p><pre>const crypto = require(&#39;crypto&#39;)<br>const knex = require(&#39;knex&#39;)(require(&#39;./knexfile&#39;))</pre><pre>module.exports = {<br>  saltHashPassword,<br>  createUser ({ username, password }) {<br>    console.log(`Add user ${username}`)<br>    const { salt, hash } = saltHashPassword(password)<br>    return knex(&#39;user&#39;).insert({<br>      salt,<br>      encrypted_password: hash,<br>      username<br>    })<br>  }<br>}</pre><pre>function saltHashPassword (password) {<br>  const salt = randomString()<br>  const hash = crypto<br>    .createHmac(&#39;sha512&#39;, salt)<br>    .update(password)<br>  return {<br>    salt,<br>    hash: hash.digest(&#39;hex&#39;)<br>  }<br>}</pre><pre>function randomString () {<br>  return crypto.randomBytes(4).toString(&#39;hex&#39;)<br>}</pre><p>Note that crypto is a native node module and need not be installed using npm.</p><p>Let’s make a migration file</p><pre>knex migrate:make encrypt_user_password</pre><p>For the migration, we are going to add encrypted_password and salt columns, then we are going to borrow the saltHashPassword method that we exported from store.js in order to migrate users already in the database. Finally, we will remove the password column.</p><pre>const { saltHashPassword } = require(&#39;../store&#39;)</pre><pre>exports.up = function up (knex) {<br>  return knex.schema<br>    .table(&#39;user&#39;, t =&gt; {<br>      t.string(&#39;salt&#39;).notNullable()<br>      t.string(&#39;encrypted_password&#39;).notNullable()<br>    })<br>    .then(() =&gt; knex(&#39;user&#39;))<br>    .then(users =&gt; Promise.all(users.map(convertPassword)))<br>    .then(() =&gt; {<br>      return knex.schema.table(&#39;user&#39;, t =&gt; {<br>        t.dropColumn(&#39;password&#39;)<br>      })<br>    })</pre><pre>  function convertPassword (user) {<br>    const { salt, hash } = saltHashPassword(user.password)<br>    return knex(&#39;user&#39;)<br>      .where({ id: user.id })<br>      .update({<br>        salt,<br>        encrypted_password: hash<br>      })<br>  }<br>}</pre><pre>exports.down = function down (knex) {<br>  return knex.schema.table(&#39;user&#39;, t =&gt; {<br>    t.dropColumn(&#39;salt&#39;)<br>    t.dropColumn(&#39;encrypted_password&#39;)<br>    t.string(&#39;password&#39;).notNullable()<br>  })<br>}</pre><p>We can’t get the original password back in the down function because it is encrypted, hence we just try our best by putting the schema back as it was.</p><p>There is a tonne of promises being used here which is common when writing migrations. Using async/await we can greatly simplify this code.</p><pre>const { saltHashPassword } = require(&#39;../store&#39;)</pre><pre>exports.up = async function up (knex) {<br>  await knex.schema.table(&#39;user&#39;, t =&gt; {<br>    t.string(&#39;salt&#39;).notNullable()<br>    t.string(&#39;encrypted_password&#39;).notNullable()<br>  })<br>  const users = await knex(&#39;user&#39;)<br>  await Promise.all(users.map(convertPassword))<br>  await knex.schema.table(&#39;user&#39;, t =&gt; {<br>    t.dropColumn(&#39;password&#39;)<br>  })</pre><pre>  function convertPassword (user) {<br>    const { salt, hash } = saltHashPassword(user.password)<br>    return knex(&#39;user&#39;)<br>      .where({ id: user.id })<br>      .update({<br>        salt,<br>        encrypted_password: hash<br>      })<br>  }<br>}</pre><pre>exports.down = function down (knex) {<br>  return knex.schema.table(&#39;user&#39;, t =&gt; {<br>    t.dropColumn(&#39;salt&#39;)<br>    t.dropColumn(&#39;encrypted_password&#39;)<br>    t.string(&#39;password&#39;).notNullable()<br>  })<br>}</pre><p>If you want to use async await, ensure you have the latest node version (it only recently became supported)</p><pre>nvm i 7</pre><p>When you install a new node version, be aware that global packages will need to be reinstalled.</p><pre>npm i knex -g</pre><p>Let’s run the migration and check that it works.</p><pre>knex migrate:latest</pre><p>If everything runs smoothly, your password should have been encrypted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8aF3WdFdTt9Zi6PsSNLKLg.png" /></figure><p>Restarting your server and creating new users should encrypt the passwords. Go to <a href="http://localhost:7555/">http://localhost:7555/</a> and create some more users to check it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-B5maFSPM4zhVMtzdcPrw.png" /></figure><pre>git add .<br>git commit -m &quot;Encrypt passwords&quot;</pre><h3>Add a login route</h3><p>At this point, let’s install nodemon to restart the server automatically when we make changes.</p><pre>npm i -g nodemon</pre><p>Now run the server using nodemon, rather than node</p><pre>nodemon .</pre><p>Next time we make changes, the server will restart for us. Usually you would leave this running and then run bash operations in a new terminal tab.</p><p>To authenticate a user we create a /login route which calls the store’s authenticate method with the username and password.</p><pre>const express = require(&#39;express&#39;)<br>const bodyParser = require(&#39;body-parser&#39;)<br>const store = require(&#39;./store&#39;)<br>const app = express()</pre><pre>app.use(express.static(&#39;public&#39;))<br>app.use(bodyParser.json())</pre><pre>app.post(&#39;/createUser&#39;, (req, res) =&gt; {<br>  store<br>    .createUser({<br>      username: req.body.username,<br>      password: req.body.password<br>    })<br>    .then(() =&gt; res.sendStatus(200))<br>})<br>app.post(&#39;/login&#39;, (req, res) =&gt; {<br>  store<br>    .authenticate({<br>      username: req.body.username,<br>      password: req.body.password<br>    })<br>    .then(({ success }) =&gt; {<br>      if (success) res.sendStatus(200)<br>      else res.sendStatus(401)<br>    })<br>})</pre><pre>app.listen(7555, () =&gt; {<br>  console.log(&#39;Server running on <a href="http://localhost:7555&#39;">http://localhost:7555&#39;</a>)<br>})</pre><p>If the authentication is successful, we respond with 200, else we respond with 401 (unauthorized).</p><p>In the store, we need to get the user’s salt, use it to encrypt the password and then check it against the encrypted_password in the database.</p><pre>const crypto = require(&#39;crypto&#39;)<br>const knex = require(&#39;knex&#39;)(require(&#39;./knexfile&#39;))</pre><pre>module.exports = {<br>  createUser ({ username, password }) {<br>    console.log(`Add user ${username}`)<br>    const { salt, hash } = saltHashPassword({ password })<br>    return knex(&#39;user&#39;).insert({<br>      salt,<br>      encrypted_password: hash,<br>      username<br>    })<br>  },<br>  authenticate ({ username, password }) {<br>    console.log(`Authenticating user ${username}`)<br>    return knex(&#39;user&#39;).where({ username })<br>      .then(([user]) =&gt; {<br>        if (!user) return { success: false }<br>        const { hash } = saltHashPassword({<br>          password,<br>          salt: user.salt<br>        })<br>        return { success: hash === user.encrypted_password }<br>      })<br>  }<br>}</pre><pre>function saltHashPassword ({<br>  password,<br>  salt = randomString()<br>}) {<br>  const hash = crypto<br>    .createHmac(&#39;sha512&#39;, salt)<br>    .update(password)<br>  return {<br>    salt,<br>    hash: hash.digest(&#39;hex&#39;)<br>  }<br>}</pre><pre>function randomString () {<br>  return crypto.randomBytes(4).toString(&#39;hex&#39;)<br>}</pre><p>We have also modified the saltHashPassword function to accept a salt, only generating one if none is supplied.</p><p>Notice that we changed the function declaration here so that the first argument is now an object. We could have easily had the hash passed in as a second argument however it is good practice to pass options objects because it makes it more obvious what is happening in the function call.</p><p>Consider for instance if saltHashPassword ends up at the bottom of the file, or is abstracted into another file. Which call is easier to understand?</p><pre>// using two arguments<br>saltHashPassword(&#39;some password&#39;, &#39;239ab09&#39;)</pre><pre>// using an options argument<br>saltHashPassword({<br>  password: &#39;some password&#39;,<br>  salt: &#39;239ab09&#39;<br>})</pre><p>Having the argument names in the call is nice.</p><p>To call /login, let’s add a login form to the index.html file.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Node database tutorial&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;form class=&quot;Login&quot;&gt;<br>    &lt;h1&gt;Login&lt;/h1&gt;<br>    &lt;input type=&quot;text&quot; class=&quot;username&quot; placeholder=&quot;username&quot;&gt;<br>    &lt;input type=&quot;password&quot; class=&quot;password&quot; placeholder=&quot;password&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Login&quot;&gt;<br>  &lt;/form&gt;<br>  &lt;form class=&quot;CreateUser&quot;&gt;<br>    &lt;h1&gt;Create account&lt;/h1&gt;<br>    &lt;input type=&quot;text&quot; class=&quot;username&quot; placeholder=&quot;username&quot;&gt;<br>    &lt;input type=&quot;password&quot; class=&quot;password&quot; placeholder=&quot;password&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Create&quot;&gt;<br>  &lt;/form&gt;<br>  &lt;script src=&quot;/app.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>and let’s add logic to the app.js to call the login endpoint</p><pre>const CreateUser = document.querySelector(&#39;.CreateUser&#39;)<br>CreateUser.addEventListener(&#39;submit&#39;, (e) =&gt; {<br>  e.preventDefault()<br>  const username = CreateUser.querySelector(&#39;.username&#39;).value<br>  const password = CreateUser.querySelector(&#39;.password&#39;).value<br>  post(&#39;/createUser&#39;, { username, password })<br>})</pre><pre>const Login = document.querySelector(&#39;.Login&#39;)<br>Login.addEventListener(&#39;submit&#39;, (e) =&gt; {<br>  e.preventDefault()<br>  const username = Login.querySelector(&#39;.username&#39;).value<br>  const password = Login.querySelector(&#39;.password&#39;).value<br>  post(&#39;/login&#39;, { username, password })<br>    .then(({ status }) =&gt; {<br>      if (status === 200) alert(&#39;login success&#39;)<br>      else alert(&#39;login failed&#39;)<br>    })<br>})</pre><pre>function post (path, data) {<br>  return window.fetch(path, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Accept&#39;: &#39;application/json&#39;,<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    },<br>    body: JSON.stringify(data)<br>  })<br>}</pre><p>By checking the status, we are now able to tell whether the user is authenticated or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-B1dpszDlxgk2iu7KewZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuAVkCp8Mqxpk2U_K64F8w.png" /></figure><p>Nice!</p><pre>git add .<br>git commit -m &quot;Login route&quot;</pre><h3>Inspecting the SQL</h3><p>Before wrapping up, let’s just take a look at some of the SQL queries being run under the covers here. In order to log a Knex query to the console, just add a .debug() to the query chain.</p><p>For example, in store.js you could add it to createUser</p><pre>knex(&#39;user&#39;).insert({<br>  salt,<br>  encrypted_password: hash,<br>  username<br>}).debug()</pre><p>Now, when this method is called, you will see the SQL output to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aW1GcKeO3xd6GaI1tiSGRQ.png" /></figure><p>By looking at the sql key and replacing the ? values with the values in the bindings array you can reconstruct the underlying SQL query that Knex runs to add a user.</p><h3>Conclusion</h3><p>In this tutorial we created a crude app for creating and logging in users using Node + Knex + MySQL. In the next tutorial we will add more functionality to the app and explore some more complex querying.</p><p>Eventually I hope to show how we can deploy the app to EC2 with a remote database.</p><p>If you liked this tutorial, then you might want to take a look at a couple of my earlier tutorials</p><ul><li><a href="https://hackernoon.com/tutorial-creating-and-managing-a-node-js-server-on-aws-part-1-d67367ac5171">https://hackernoon.com/tutorial-creating-and-managing-a-node-js-server-on-aws-part-1-d67367ac5171</a></li><li><a href="https://hackernoon.com/tutorial-creating-and-managing-a-node-js-server-on-aws-part-2-5fbdea95f8a1">https://hackernoon.com/tutorial-creating-and-managing-a-node-js-server-on-aws-part-2-5fbdea95f8a1</a></li></ul><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fdde502%2F&amp;image=https%3A%2F%2Fucarecdn.com%2F57662ddc-da7c-407b-afcb-cb45184b2705%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d25dd15e8727342107fbe0b6d67b030e/href">https://medium.com/media/d25dd15e8727342107fbe0b6d67b030e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f2461bdd77f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/setting-up-node-js-with-a-database-part-1-3f2461bdd77f">Tutorial: Setting up Node.js with a database</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Creating and managing a Node.js server on AWS, part 2]]></title>
            <link>https://medium.com/hackernoon/tutorial-creating-and-managing-a-node-js-server-on-aws-part-2-5fbdea95f8a1?source=rss-e66d0c67becc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fbdea95f8a1</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Robert Tod]]></dc:creator>
            <pubDate>Wed, 11 Jan 2017 15:38:55 GMT</pubDate>
            <atom:updated>2017-07-14T21:04:41.119Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://hackernoon.com/tutorial-creating-and-managing-a-node-js-server-on-aws-part-1-d67367ac5171">part 1</a> we started a server, responding to HTTP requests on port 3000. In this tutorial we will look at 4 more concepts</p><ul><li>Serving HTTP traffic on the standard port, 80</li><li>Keeping the Node.js process running</li><li>Deploying code into the server</li><li>Serving some HTML</li></ul><h3>Serving HTTP traffic on the standard port, 80</h3><p>Paste this URL into a URL bar in a new tab.</p><pre><a href="http://imgur.com/">http://imgur.com:80/</a></pre><p>You will notice the 80 gets dropped in the URL bar. That’s because port 80 is the default port for HTTP traffic.</p><p>HTTPS traffic uses port 443. Try Hacker News.</p><pre><a href="https://news.ycombinator.com/">https://news.ycombinator.com</a><a href="https://www.google.com/">:443/</a></pre><p>Because these ports are often public, you need special privileges to run processes using them. Also, it is not great to run Node.js on port 80 or 443 directly because you may want to open up a few different applications on these ports. With a router you will be able to send traffic from port 80 or 443 to any program you wish, depending on the headers of the incoming HTTP request.</p><p>There are few great choices for a router, but I find that <a href="https://www.nginx.com/resources/wiki/">nginx</a> is generally the best tool for most things. It’s great for building your first ever app, or when you need to scale up to millions of visitors.</p><p>Before beginning, start your server if it is stopped and SSH into it (<a href="https://hackernoon.com/tutorial-creating-and-managing-a-node-js-server-on-aws-part-1-d67367ac5171">as shown in the last tutorial</a>). Once logged in, we can install <strong><em>nginx</em></strong>.</p><p>Ubuntu comes with it’s own package manager, <strong><em>apt-get</em></strong>. Using <strong><em>apt-get</em></strong>, we can install <strong><em>nginx</em></strong> in one command.</p><pre>sudo apt-get install nginx</pre><p>Most Linux distributions come with a package manager, so Google your version if <strong><em>apt-get</em></strong> doesn’t work. <strong><em>apt-get</em></strong> runs nginx automatically after install so you should now have it running on port 80, check by entering your public DNS URL into a browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUYY-2e61Rm8ZgYZ-0WKaQ.png" /><figcaption>Default nginx page</figcaption></figure><p>If this doesn’t work, you might need to start it manually.</p><pre>sudo /etc/init.d/nginx start</pre><p>If you are still can’t reach the server then check out Stack Overflow or post a comment here.</p><p>We need to configure <strong><em>nginx</em></strong> to route port 80 traffic to port 3000. <strong><em>nginx</em></strong> has config placed in the /etc/nginx/sites-available folder where there is already a default config which serves the <strong><em>nginx</em></strong> welcome page we saw earlier.</p><p>You can take a look at this config using cat.</p><pre>cat /etc/nginx/sites-available/default</pre><p>How are <strong><em>nginx</em></strong> configs set up? Configs are stored in plain text files in sites-available with any name. Linking them into the sites-enabled folder will cause them to be read and used when <strong><em>nginx</em></strong> starts. All of the configs are combined together by <strong><em>nginx</em></strong>.</p><p>Let’s first remove the default config from sites-enabled, we will leave it in sites-available for reference.</p><pre>sudo rm /etc/nginx/sites-enabled/default</pre><p>Create a config file in sites-available and name it whatever you like.</p><pre>sudo nano /etc/nginx/sites-available/tutorial</pre><p>The following is the config we are going to use.</p><pre>server {<br>  listen 80;<br>  server_name tutorial;<br>  location / {<br>    proxy_set_header  X-Real-IP  $remote_addr;<br>    proxy_set_header  Host       $http_host;<br>    proxy_pass        <a href="http://127.0.0.1:3000;">http://127.0.0.1:3000;</a><br>  }<br>}</pre><p>This will forward all HTTP traffic from port 80 to port 3000.</p><p>Link the config file in sites enabled (this will make it seem like the file is actually copied insites-enabled).</p><pre>sudo ln -s /etc/nginx/sites-available/tutorial /etc/nginx/sites-enabled/tutorial</pre><p><a href="https://kb.iu.edu/d/abbe">Read more about symbolic links here if they are unfamiliar.</a></p><p>Restart <strong><em>nginx</em></strong> for the new config to take effect.</p><pre>sudo service nginx restart</pre><p>If you did not stop/start the server since the last tutorial then you may still have your node application running.</p><pre># list background jobs<br>jobs</pre><p>If your application shows up then no need to run it again. If it is not running then you need to start it.</p><pre>node tutorial/index.js</pre><p>Once the server is running, press ctrl+z, then resume it as a background task.</p><pre>bg %1</pre><p>Now visit your server’s public DNS URL, using port 80.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJuDpQ6q_gH8xohJtOf35w.png" /></figure><p>The server is running on port 80!</p><h3>Keeping the Node.js process running</h3><p>It’s quite tedious using ctrl+z to pause a process, and then running it in the background. Also, doing it this way will not allow the Node.js process to restart when you restart your server after an update or crash.</p><p>Before moving forward, stop your running node process</p><pre># Nukes all Node processes<br>killall -9 node</pre><p>To keep these processes running we are going to use a great NPM package called <a href="http://pm2.keymetrics.io/">PM2</a>. While in an SSH session, install PM2 globally.</p><pre>npm i -g pm2</pre><p>To start your server, simply use pm2 to execute index.js.</p><pre>pm2 start tutorial/index.js</pre><p>To make sure that your PM2 restarts when your server restarts</p><pre>pm2 startup</pre><p>This will print out a line of code you need to run depending on the server you are using. Run the code it outputs.</p><p>Finally, save the current running processes so they are run when PM2 restarts.</p><pre>pm2 save</pre><p>That’s it! You can log out/in to SSH, even restart your server and it will continue to run on port 80.</p><p>To list all processes use</p><pre>pm2 ls</pre><p>Your process will have a pretty generic name, something like index, which would be hard to differentiate if you had a few other microservices running on the server too. Let’s stop the process, remove it and start it back up with a nicer name.</p><pre># Use the number listed in pm2 ls<br># to stop the daemon<br>pm2 stop index</pre><pre># Remove it from the list<br>pm2 delete index</pre><pre># Start it again, but give it a<br># catchy name<br>pm2 start tutorial/index.js --name “Tutorial”</pre><p>Great! Check out the <a href="http://pm2.keymetrics.io/">PM2 docs</a> to see what else you can do with process management.</p><h3>Deploying code into the server</h3><p>Instead of writing code in an SSH session, let’s push the code to a git repo in Github, SSH into the server and pull in the new code.</p><p>Go to <a href="https://github.com/">Github</a> or your favourite source control website, login and create a new repository named what you like. If you aren’t able to make it private, make it public (it’s okay, no one’s going to look anyway).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-J63Z8cg_--d91hiUVvoQ.png" /></figure><p>Make a new directory wherever you like to put your code projects <strong>locally</strong> (btw, to exit an SSH session just type exit). I named mine with gusto and imagination, “tutorial-pt-2&quot;.</p><pre>cd ~/Code<br>mkdir tutorial-pt-2<br>cd tutorial-pt-2</pre><p>Now set up your origin, make an empty commit and push it up, setting your upstream branch as master.</p><pre>git init<br>git commit --allow-empty -m &quot;Well this is my first commit, *yay*&quot;</pre><pre># Use your repo&#39;s origin URL here<br>git remote add origin <a href="/service/mailto:git@github.com">git@github.com</a>:roberttod/tutorial-pt-2.git<br>git push -u origin master</pre><p><a href="https://coderwall.com/p/m_pgbg/start-git-repos-with-an-empty-commit">It’s nice to start with an empty commit</a> :).</p><p>Like we did on the server run npm init and then create an index.js file using the same code from the last tutorial. <strong><em>P.S. I am missing out the </em></strong><strong><em>;s on purpose, check out </em></strong><a href="https://github.com/feross/standard"><strong><em>Standard Style</em></strong></a><strong><em>.</em></strong></p><pre>const express = require(&#39;express&#39;)<br>const app = express()<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;HEY!&#39;)<br>})</pre><pre>app.listen(3000, () =&gt; console.log(&#39;Server running on port 3000&#39;))</pre><p>NPM install express</p><pre>npm install express --save</pre><p>Also, let’s add a .gitignore file so that we don’t check in the node_modules directory. .DS_Store files always get added to directories by OSX, they contain folder meta data. We want to ignore these too.</p><pre>node_modules<br>.DS_Store</pre><p>In general, it is best to only check in code that you actually need checked in, if you ever find yourself with chunks of copied or library code in your git repo then there is probably a better way to do it.</p><p>Now add all your code and push it up</p><pre>git add .<br>git commit -m &quot;Ze server.&quot;<br>git push</pre><p>Now we need to pull the code into the server. This is where it can be kind of tricky.</p><p>We need to SSH into the server, generate a SSH private/public key pair and then add it as a deployment key in source control (i.e. Github). Only when the server is allowed access to the remote repo will it be able to clone the code and pull down changes.</p><p>SSH into your server and generate the key pair.</p><pre># When prompted, use the default name.<br># No need for a pass phrase.<br>ssh-keygen -t rsa</pre><p>Show the contents of the file</p><pre>cat ~/.ssh/id_rsa.pub</pre><p>Select the key’s contents and copy it into Github. Deploy keys are added in a section called <strong><em>Deploy keys</em></strong> in the settings for your repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HMWr0HE17bceQknNVZEOg.png" /></figure><p>Paste your key and call it something meaningful.</p><p>Whenever you are logged in over SSH, you want the keys to be added so that they are used to authenticate with Github. To do this, add these lines to the top of your ~/.bashrc file.</p><pre># Start the SSH agent<br>eval `ssh-agent -s`</pre><pre># Add the SSH key<br>ssh-add</pre><p>This will make sure you use the keys whenever you log on to the server. To run the code without logging out, execute the .bashrc file</p><pre>source ~/.bashrc</pre><p>Now we can clone the repo! Remove any previous code on the server and in the user directory, clone the repo</p><pre># You should use your own git URL.<br>git clone git@github.com:roberttod/tutorial-pt-2.git</pre><p>If it works, it will allow you to type “yes” to add github as a known host, then the repo will be downloaded.</p><p>In a nice world we like to completely avoid ever using SSH. For deployment, we are going to use PM2 in order for us to do the git cloning on the server for us, with some bonus features.</p><p>Before using PM2, remove the code you just pulled in from git into your server.</p><pre>rm -rf ~/tutorial-pt-2</pre><p>While you are still in the SSH session, ensure that there are no processes still running on PM2, if there are then remove them.</p><pre>pm2 ls</pre><pre># Only do this if a task is still running<br>pm2 delete tutorial</pre><p>In your <strong>local</strong> version of the project, install PM2 globally</p><pre>npm i -g pm2</pre><p>Now we need to add a config file PM2 can read so that it knows how to deploy.</p><p>PM2 configs are fully explained in the <a href="http://pm2.keymetrics.io/docs/usage/application-declaration/">PM2 docs</a>. The config file can be auto generated but I prefer to just create my own from scratch, avoiding any config I don’t need.</p><p>The config file should be named ecosystem.config.js and should look like this</p><pre>module.exports = {<br>  apps: [{<br>    name: &#39;tutorial-2&#39;,<br>    script: &#39;./index.js&#39;<br>  }],<br>  deploy: {<br>    production: {<br>      user: &#39;ubuntu&#39;,<br>      host: &#39;ec2-52-209-166-225.eu-west-1.compute.amazonaws.com&#39;,<br>      key: &#39;~/.ssh/tutorial-2.pem&#39;,<br>      ref: &#39;origin/master&#39;,<br>      repo: &#39;<a href="/service/mailto:git@github.com">git@github.com</a>:roberttod/tutorial-pt-2.git&#39;,<br>      path: &#39;/home/ubuntu/tutorial-2&#39;,<br>      &#39;post-deploy&#39;: &#39;npm install &amp;&amp; pm2 startOrRestart ecosystem.config.js&#39;<br>    }<br>  }<br>}</pre><p>You will need to add your own host in the config file.</p><p>How does PM2 use this config file? When you run pm2 deploy ..., PM2 SSHs into your server, clones your repo into the directory specified in path, then it runs the post-deploy on the server (so it starts your server using the PM2 installed globally on the server). After the deploy, you will be able to run pm2 ls on the server to see all the apps running, their names will be the same as specified in the config file.</p><p>Once the file is saved, setup the directories on the remote</p><pre>pm2 deploy ecosystem.config.js production setup</pre><p>If you run into any auth issues, look back at setting up the SSH agent to make sure you didn’t miss anything.</p><p>Once setup, commit and push your changes to Github so that when it clones it gets your ecosystem.config.js file, which is going to be used to start your app using PM2 on the server.</p><pre>git add .<br>git commit -m &quot;Setup PM2&quot;<br>git push</pre><p>Now you can run the deploy command</p><pre>pm2 deploy ecosystem.config.js production</pre><p>This should come up with an error, which will be that npm was not found.</p><p>The reason for this is because of some code in the .bashrc file of the server. This code stops the file from running if the shell is not <strong><em>interactive</em></strong>. Unlike using ssh, PM2 logs into the server in a <strong><em>non-interactive</em></strong> shell. NVM is set up in the .bashrc file so PM2 isn’t running NVM, which adds the npm executable (thus the error from PM2). <a href="http://www.tldp.org/LDP/abs/html/intandnonint.html">Read more about interactive/non interactive shells.</a></p><p>SSH into your server and open up the ~/.bashrc file. The code that excludes <strong><em>non-interactive</em></strong> sessions is near the top.</p><pre># If not running interactively, don&#39;t do anything</pre><pre>case $- in<br>  *i*) ;;<br>  *) return;;<br>esac</pre><p>This code is some magic bash shit. All we need to do is move the NVM code above this code, so it always executes. Find the following lines and move them above the case statement</p><pre>export NVM_DIR=&quot;/home/ubuntu/.nvm&quot;<br>[ -s &quot;$NVM_DIR/nvm.sh&quot; ] &amp;&amp; . &quot;$NVM_DIR/nvm.sh&quot;  # This loads nvm</pre><p>Save and exit.</p><p>Back on your local terminal, try running the PM2 deploy again</p><pre>pm2 deploy ecosystem.config.js production</pre><p>It should work this time! And your server should still be running when you check in a browser.</p><p>Using a global PM2 on the server and a global PM2 on the client is a bit messy. It would be better if our code used the local version of the PM2 package. To do this, add a deploy and restart script to your package.json</p><pre>...<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;restart&quot;: &quot;pm2 startOrRestart ecosystem.config.js&quot;,<br>    &quot;deploy&quot;: &quot;pm2 deploy ecosystem.config.js production&quot;,<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;repository&quot;: {<br>...</pre><p>Install PM2 locally and save, using --save-dev</p><pre>npm i pm2 --save-dev</pre><p>For those not that familiar with NPM, adding --save or --save-dev adds the package, along with a version number to package.json. Any packages in the package.json file will be installed when running npm install, which happens in the PM2 post-deploy.</p><p>Before deploying, commit all your changes and push to git.</p><p>When you run npm deploy, it will now use the local version of PM2. Neat!</p><pre>npm run-script deploy</pre><p>In case you find that your app isn’t running, check the PM2 logs on your server, located in ~/.pm2/logs/.</p><p>To make sure the app restarts when the server restarts, SSH back into your server and run</p><pre>pm2 save</pre><p>The only PM2 process running should be your deployed server, so PM2 will ensure that is always kept running.</p><h3>Serving HTML</h3><p>Before concluding the tutorial, let’s use our deployment setup to change the server so that it serves HTML, rather than just responding with “Hey”.</p><p>Remove the route handler for / and set up a static directory that express will use to serve static files.</p><pre>const express = require(&#39;express&#39;)<br>const app = express()</pre><pre>app.use(express.static(&#39;public&#39;))<br>app.listen(3000, () =&gt; console.log(&#39;Server running on port 3000&#39;))</pre><p>By calling express.static with “public”, static files will be served from the public directory. If we add an index.html in /public, then this will be automatically served at / by express (if we left a custom / handler, then that would override this functionality).</p><p>Save a simple HTML file in public/index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Erm hey.&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;img src=&quot;<a href="https://media.giphy.com/media/3o6Zt7aSSZLX6U5WtW/source.gif">https://media.giphy.com/media/3o6Zt7aSSZLX6U5WtW/source.gif</a>&quot;&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Commit these changes (perhaps you could check the server still works by running node index.js locally and visiting <a href="http://localhost:3000/">http://localhost:3000</a>).</p><p>Deploy the changes</p><pre>npm run-script deploy</pre><p>Your server will now respond with your static HTML page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVufB3ETrKZiZVr4nH__6g.png" /></figure><h3>Conclusion</h3><p>You should now have a simple express app that is fairly easy to deploy on EC2, running on port 80. I left my source code public in case you would like to take a look <a href="https://github.com/roberttod/tutorial-pt-2">https://github.com/roberttod/tutorial-pt-2</a>.</p><p>If you like this tutorial, I am doing a few more explaining <a href="https://medium.com/@bobtodski/setting-up-node-js-with-a-database-part-1-3f2461bdd77f">how to setup Node with MySQL</a>.</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fbdea95f8a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/tutorial-creating-and-managing-a-node-js-server-on-aws-part-2-5fbdea95f8a1">Tutorial: Creating and managing a Node.js server on AWS, part 2</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Creating and managing a Node.js server on AWS, part 1]]></title>
            <link>https://medium.com/hackernoon/tutorial-creating-and-managing-a-node-js-server-on-aws-part-1-d67367ac5171?source=rss-e66d0c67becc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d67367ac5171</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ec2]]></category>
            <dc:creator><![CDATA[Robert Tod]]></dc:creator>
            <pubDate>Tue, 20 Dec 2016 13:43:09 GMT</pubDate>
            <atom:updated>2017-07-14T19:47:17.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>There are many ways to run servers and plenty of cloud platforms to do so. To start this tutorial series I am going to go with managing an EC2 server using AWS (Amazon Web Services), which is down to the metal and probably the most common way to run Node.js applications.</p><p>This tutorial series is intended to help get a better understanding of cloud based servers, though there will be small parts showing how to set up a simple Node.js app.</p><p>I find that most tutorials for configuring AWS or cloud servers often expect quite a bit of knowledge and can be quite daunting. For the most part there is quite a bit of reading between the lines to get through. I hope that this is quite simple to follow. To make it as simple as possible I will be writing it with Mac users in mind but if you are using Linux then it won’t be much of an issue, we will just be using bash and a text editor.</p><p>This part will cover</p><ul><li>starting an AWS server</li><li>SSH into your server</li><li>installing Node.js</li><li>creating a public HTTP endpoint that responds with a static message</li></ul><h3>Creating and starting the server</h3><p>If you haven’t created an AWS account, open <a href="https://aws.amazon.com/">https://aws.amazon.com/</a>, and then choose <strong><em>Create an AWS Account</em></strong>. Follow the steps to get an account setup.</p><p>Once logged into your AWS account we are going to create an EC2 machine. EC2 stands for <em>Amazon Elastic Compute Cloud. </em>The compute cloud is just a load of computers in Amazon’s datacenters that are connected to the internet and can be controlled by using the AWS dashboard. We are going to take one of those machines and set it up for our use.</p><p>Click <strong><em>services</em></strong> on the navigation bar and select EC2, which is under the <strong><em>compute</em></strong> category. Click <strong><em>launch instance</em></strong>. You will be presented with a bunch of options which are various different images. An image is an exact copy of a hard drive that can be easily loaded onto an empty hard drive, in this case they are being used as presets to get your machine setup easily. Without at least an operating system and SSH, it wouldn’t be possible to even configure the instance so some preset software is necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJR0OCEtnci11pr6UBiN2g.png" /><figcaption>Selecting an image</figcaption></figure><p>The options include different versions of Windows and Linux. Most servers run Linux and it is a great choice for developing Node.js, Windows servers are only really useful for specialized applications such as .NET *shudder*. For the basic things we will be doing in this tutorial, there isn’t much difference between the Linux images. I chose to go with <strong><em>Ubuntu Server</em></strong> because it is widely used and has tonnes of guides and plenty of questions and answers on Stack Overflow.</p><p>Once an image has been selected, we need to select an instance type. Notice that this is a <strong><em>virtual server</em></strong>, with <strong><em>virtual CPUs</em></strong>. Virtual means that although it will seem like we are connecting to and configuring one computer, in fact Amazon will be running multiple instances on the same machine while pretending it isn’t, which is great for scaling and pricing. Let’s choose <strong><em>t2.micro</em></strong> which is eligible for the <a href="https://aws.amazon.com/free/">free tier</a>, so if your account is less than 12 months old you can run your server for free. Thanks Amazon!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLEHnWw2_Hot0_YIiAGGzg.png" /><figcaption>Selecting an instance type</figcaption></figure><p>After you have selected your instance type, click <strong><em>Next: Configure Instance Details</em></strong>. The following page is more complicated but you can ignore most of it for now, we may explore these options later.</p><p>Click <strong><em>Next: Add Storage</em></strong>. The default is 8GB of an SSD which is fine for us. Click <strong><em>Next: Add Tags</em></strong>. We don’t need any tags but they are useful for when you have a large number of instances and you need to filter and search through them.</p><p>Click <strong><em>Next: Configure Security Group</em></strong>. A security group is a config for your server, telling it which ports it should expose to which IP addresses for certain types of traffic. Name the group something meaningful, I chose <strong><em>tutorial group</em></strong>.</p><p>To run our app we are going to need SSH access, which by default is on port 22 and uses the TCP protocol. Amazon adds this in for us by default. There is a warning about the source being 0.0.0.0/0 which allows us to SSH from any IP address however this is fine. If you were deploying and configuring your app from a VPN or company network then you could limit SSH access only for that IP which is a good security precaution when running something in production, but SSH access requires the correct SSH key so it is completely secure without this measure.</p><p>Since we would like to also serve an app we need to expose a HTTP port publicly, by default this is port 80 (but browsers strip this so you don’t see it in URLs). Click <strong><em>Add Rule</em></strong> and select the type as <strong><em>HTTP</em></strong>, the default settings for this will use TCP as the protocol and expose port 80 to all IPs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRsK_NjW6wYR9i8kDwM3iQ.png" /><figcaption>Configuring a security group</figcaption></figure><p>To launch the instance, click <strong><em>Review and Launch, </em></strong>then click<strong><em> Launch</em></strong>. You will be prompted to setup an SSH key which will give you access to the instance. Choose <strong><em>create a new key pair</em></strong>, and name the key, I named it “tutorial”. Click <strong><em>Download Key Pair</em></strong>. This should download a .pem file which can be used to SSH into the server. Keep this file safe because anyone can connect to your server using it, if you lose the file you will need to generate a new one.</p><p>Click <strong><em>Launch Instance</em></strong>. Click <strong><em>View Instances</em></strong>. Woo! Your instance should be booting up. Once the <strong><em>Instance State</em></strong> is <strong><em>Running</em></strong> then you are ready to SSH in.</p><p><strong><em>Note:</em></strong> Remember to stop the instance when you aren’t running it! To do that just right click on the instance, under <strong><em>Instance State</em></strong> click <strong><em>Stop</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25YIcjkNeRUSwG7rL-d6nQ.png" /><figcaption>Stopping an instance</figcaption></figure><h3>SSH into your server</h3><p>Generally, the correct place to put your .pem file is in your .ssh folder, in your user directory. The .ssh folder is a hidden folder, to open it in finder open terminal and execute the open command.</p><pre># The open command will open the<br># given path using the default system<br># application for the file type. For<br># folders it uses finder!<br>$ open ~/.ssh</pre><p>Once the .pem file is in your ssh folder, use chmod to set permissions so that it can be used as a key.</p><pre>$ chmod 400 ~/.ssh/whatever-your-key-name-is.pem</pre><p>To SSH we need to have a username, an address and a key. The address is available when we click on our instance in the EC2 instances dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ockW62GV_RnFxcUoLjLrkQ.png" /><figcaption>Instance details</figcaption></figure><p>The instance I setup has a public IP 52.214.64.31 which I could use to connect, giving the .pem file as a key using the -i flag.</p><pre># Don&#39;t actually run this command<br>$ ssh -i ~/.ssh/whatever-your-key-name-is.pem 52.214.64.3</pre><p>However it is more correct to use the public DNS (the only real difference though is when you are connecting from EC2 machine to EC2 machine then the DNS will resolve to the private IP rather than the public IP).</p><pre># Don&#39;t run this command either<br>$ ssh -i ~/.ssh/whatever-your-key-name-is.pem ec2-52-214-64-31.eu-west-1.compute.amazonaws.com</pre><p>Almost there. By default, connecting to your instance without a username will try to login as root which is generally not allowed. By right clicking your instance and selecting <strong><em>connect</em></strong> we can see what the correct username is. This is dependant on the image you chose, for ubuntu the username is by default ubuntu. You can see the username in the <strong><em>Example</em></strong> section of the dialogue, it is the part before the @ symbol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXhzy4hfCWeEbjFOYQ-SvA.png" /><figcaption>Finding the SSH username</figcaption></figure><p>To connect, the SSH command should look something like</p><pre># Fill in your specific details for this to work.<br>$ ssh -i ~/.ssh/whatever-your-key-name-is.pem ubuntu@ec2-52-214-64-31.eu-west-1.compute.amazonaws.com</pre><p>This should connect you to your instance, just type yes when prompted so that you can add your instance as a known host. You’re connected!</p><h3>Installing node and system dependencies</h3><p>Once in an SSH session the first thing to do is get Node.js. <a href="https://github.com/creationix/nvm">NVM (Node Version Manager)</a> is a pretty great way to install Node.js and allows you to easily switch versions if required.</p><p>To install NVM just run this command (same as in the NVM installation instructions).</p><pre>$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash</pre><p>This command pulls down a script from a remote URL and runs it. You now have NVM! But if you run nvm ls you will notice it isn’t found. This is because NVM adds some code to your ~/.bashrc. This file is a special file that is run every time you log in to your instance, so to get NVM running you could logout and login again. However you can just run the file manually by using the source command.</p><pre>$ source ~/.bashrc</pre><p>Now running nvm ls works! But there aren’t any node versions installed! To get the latest version, just nvm install &lt;latest version number&gt;.</p><pre>$ nvm install 7</pre><p>To check node is ready to go just echo the version.</p><pre>$ node --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2mCDmWJzW8MhcQjIpBRjg.png" /><figcaption>Installing node</figcaption></figure><p>Node.js is installed!</p><h3>Creating a public HTTP endpoint</h3><p>Before concluding this part of the tutorial we are going to make a public URL anyone can request from the browser to get a response from the server.</p><p>Make a directory for the server and cd into it.</p><pre>$ mkdir server<br>$ cd server</pre><p>Now you are in your server directory, you need to npm init</p><pre>$ npm init</pre><p>This will create a package.json file which will be used to track any dependencies we use. npm init will ask for a load of info, I tend to just press enter to use all the defaults.</p><p>All we will need to run our server is the express package. To install express and add it to package.json.</p><pre>$ npm install express --save-dev</pre><p>Note that now you should have a node_modules directory and package.json</p><pre>$ ls</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*aQelypyf2C8jeIRYQdSUiA.png" /></figure><p>Now we just need to add some code to run the server. We will use nano to write the server in an index.js file.</p><pre>$ nano index.js</pre><p>The server I used just responds with “HEY!” when you do a request to /. I listen to requests on port 3000.</p><pre>const express = require(&#39;express&#39;)<br>const app = express()</pre><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;HEY!&#39;)<br>})</pre><pre>app.listen(3000, () =&gt; console.log(&#39;Server running on port 3000&#39;))</pre><p>Press ctrl+x to exit, ensuring you save when you exit by pressing y followed by enter.</p><p>Now we can use node to start the server!</p><pre>$ node index.js</pre><p>Once listening, this should log “Server running on port 3000”. You may have noticed however we didn’t open our server traffic to port 3000, we opened it to port 80. Port 80 is a privileged port and running the server there using Node.js is unusual, generally using a router is better. If you change the index.js file to use 80 and then run node index.js you will notice you get a permission denied error.</p><p>In the next tutorial we will go through adding a router to use port 80, but for now let’s just open up port 3000 so we can test our server.</p><p>Leave your server running and go to the <strong>Security Groups</strong> tab in the EC2 console. Right click the security group you setup and click <strong><em>edit inbound rules</em></strong>. Click <strong><em>Add Rule</em></strong>. This time we are going to use a custom TCP rule on port 3000, open to anywhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuzuWfaIsittNBeAhU2HcQ.png" /><figcaption>Opening up port 3000 to TCP traffic</figcaption></figure><p>Click Save. We should now have access to our server! Using a browser, visit your public DNS URL with port 3000 and you should see the HEY! response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hCAp9YGfhF7tc198YTNOA.png" /><figcaption>The response from your server</figcaption></figure><p>To leave the server running when we log out, we need to press ctrl+z to pause the process (this only works when your server is running, node index.js). When you press ctrl+z you will be presented with all jobs, in this case the only one there will be the Node.js job that was paused.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*xleLw24KhRGEgpYgH3b7vg.png" /></figure><p>You can see that the job number for node index.js is 1 (as noted by [1]+). To run that in the background, use the bg command.</p><pre>$ bg %1</pre><p>Then logout</p><pre>$ exit</pre><p>You should still be able to access your URL and see the “HEY!” response.</p><h3>Conclusion</h3><p>If everything went well we should have a simple Node.js app which is accessible from a public URL anywhere in the world!</p><p>To stop the instance just navigate to the <strong><em>Instances</em></strong> tab in the EC2 dashboard, right click on your instance and in <strong><em>Instance</em></strong> <strong><em>State</em></strong> click <strong><em>Stop</em></strong>.</p><p>In the next tutorial I intend to cover</p><ul><li>running the app on port 80 using nginx</li><li>using PM2 to keep the app running after a restart</li><li>using PM2 to deploy the app from a local directory</li></ul><p>Let me know in the comments section if there is anything I missed or is a bit confusing!</p><p><a href="https://medium.com/@bobtodski/tutorial-creating-and-managing-a-node-js-server-on-aws-part-2-5fbdea95f8a1#.mnlkymeti">Part 2 is now available.</a></p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d67367ac5171" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/tutorial-creating-and-managing-a-node-js-server-on-aws-part-1-d67367ac5171">Tutorial: Creating and managing a Node.js server on AWS, part 1</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>