{"componentChunkName":"component---src-templates-category-js","path":"/category/how-to","result":{"data":{"allContentfulPost":{"edges":[{"node":{"slug":"webinar-the-end-of-monoliths-a-guide-to-backend-architecture-in-2020","title":"Webinar: The end of monoliths? A guide to backend architecture in 2020","image":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/49RQOiTJCrILQmaTM9BZDT/b5a09b357e0702310032d2190818b1b5/maxresdefault.jpg","fileName":"maxresdefault.jpg"}},"bodyContent":{"childMarkdownRemark":{"html":"<p>You can’t build a stable backend without solid architecture. And without proper backend, you can’t develop a good application. But what does stable backend mean? How to keep up with all the architectural trends in an ever-changing, fast-paced reality of the modern development? 📈</p>\n<p>Is monolithic architecture already dead? Should you or your team focus on practicing the use of microservices? Is following the trends a good approach or should you rather lean on some thoroughly tested solutions? 🤔</p>\n<p>During our upcoming webinar, Adam Polak –  Head of Node.js Team at The Software House, will guide you through the current backend architecture trends and solutions, indicating the most important (but not always obvious) issues that you should pay attention to. Here’s the excerpt from the extensive agenda:</p>\n<ul>\n<li>analysis of some important elements of backend: architecture, infrastructure, environment, communication;</li>\n<li>monolithic architecture – still a good idea?</li>\n<li>modular monolith vs microservices;</li>\n<li>why the most of the services is still monolithic-based?</li>\n<li>what were the most significant changes in the architecture in the last few years?</li>\n<li>REST API, BFF, GraphQL and the communication;</li>\n<li>what does a stable backend mean in 2020?</li>\n</ul>\n<p>Subjects discussed during our event will be 100% based on real-life cases and experiences. Also, Adam will answer your questions during a Q&#x26;A session after the webinar. The whole event will last for approximately an hour.</p>"}},"categories":[{"name":"Node.js","slug":"node-js"},{"name":"How To","slug":"how-to"}]}},{"node":{"slug":"node-is-simple-part-4","title":"Node Is Simple - Part 4","image":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/5cQGAuhcwdad8tw1hv1qAx/e6bc1591fdd4f6387fdb9cc4ddede1a2/4.png","fileName":"4.png"}},"bodyContent":{"childMarkdownRemark":{"html":"<p><strong><em>tl;dr</em></strong> — <em>This is the fourth article of the</em> <strong><em>Node is Simple</em></strong> <em>article series. In this article series, I will be discussing how to create a simple and secure NodeJS, Express, MongoDB web application.</em></p>\n<p>To follow the past tutorials, <a href=\"https://node.dev/post/node-is-simple-part-1\">Node is Simple Part 1</a>, <a href=\"https://node.dev/post/node-is-simple-part-2\">Node is Simple Part 2</a> and <a href=\"https://node.dev/post/node-is-simple-part-3\">Node is Simple Part 3</a>.</p>\n<p>Hello fellow developers, now you’ve come across this article series, let’s get to it, shall we. In the past articles, I have discussed how to create simple CRUD endpoints, with MongoDB as the database and how to use Postman to test the endpoints. So in this tutorial, I will discuss how to upload files to MongoDB using MongoDB GridFS and view (or stream) them.</p>\n<h2>So what is this GridFS?</h2>\n<p>We can upload files to a folder easily with <a href=\"http://expressjs.com/en/resources/middleware/multer.html\">Multer-Middleware</a>. This is a good reference for that.</p>\n<p><a href=\"https://medium.com/quick-code/uploading-files-and-serve-directory-listing-using-nodejs-6f353f65be5\">Uploading Files and Serve Directory Listing Using NodeJS</a></p>\n<p>But I am going to discuss how to use MongoDB as the file storage. However, there is a little hiccup, where you can only store 16MB as a document in MongoDB BSON format. To overcome this issue, there is a feature called <a href=\"https://docs.mongodb.com/manual/core/gridfs/\">GridFS</a>.</p>\n<blockquote>\n<p>Instead of storing a file in a single document, GridFS divides the file into parts, or chunks <a href=\"https://docs.mongodb.com/manual/core/gridfs/#chunk-disambiguation\">[1]</a>, and stores each chunk as a separate document.</p>\n</blockquote>\n<h2>Enough with the theory</h2>\n<p>Yes, let’s move on to implementation. First, we have to create a GridFS driver. Let’s create <em>gridfs-service.js</em> file inside <em>/database</em> directory.</p>\n<pre><code>const mongoose = require(\"mongoose\");\nconst config = require(\"../config\");\nconst dbPath = config.MONGO_URI;\nconst chalk = require(\"chalk\");\n\nconst GridFsStorage = require(\"multer-gridfs-storage\");\nconst Grid = require(\"gridfs-stream\");\nGrid.mongo = mongoose.mongo;\n\nconst conn = mongoose.createConnection(dbPath, {\n  useNewUrlParser: true,\n  useUnifiedTopology: true,\n  useCreateIndex: true,\n  useFindAndModify: false\n});\n\nconn.on(\"error\", () => {\n  console.log(chalk.red(\"[-] Error occurred from the database\"));\n});\n\nlet gfs, gridFSBucket;\n\nconn.once(\"open\", () => {\n  gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db, {\n    bucketName: \"file_uploads\"\n  });\n  // Init stream\n  gfs = Grid(conn.db);\n  gfs.collection(\"file_uploads\");\n  console.log(\n    chalk.yellow(\n      \"[!] The database connection opened successfully in GridFS service\"\n    )\n  );\n});\n\nconst getGridFSFiles = id => {\n  return new Promise((resolve, reject) => {\n    gfs.files.findOne({ _id: mongoose.Types.ObjectId(id) }, (err, files) => {\n      if (err) reject(err);\n      // Check if files\n      if (!files || files.length === 0) {\n        resolve(null);\n      } else {\n        resolve(files);\n      }\n    });\n  });\n};\n\nconst createGridFSReadStream = id => {\n  return gridFSBucket.openDownloadStream(mongoose.Types.ObjectId(id));\n};\n\nconst storage = new GridFsStorage({\n  url: dbPath,\n  cache: true,\n  options: { useUnifiedTopology: true },\n  file: (req, file) => {\n    return new Promise(resolve => {\n      const fileInfo = {\n        filename: file.originalname,\n        bucketName: \"file_uploads\"\n      };\n      resolve(fileInfo);\n    });\n  }\n});\n\nstorage.on(\"connection\", () => {\n  console.log(chalk.yellow(\"[!] Successfully accessed the GridFS database\"));\n});\n\nstorage.on(\"connectionFailed\", err => {\n  console.log(chalk.red(err.message));\n});\n\nmodule.exports = mongoose;\nmodule.exports.storage = storage;\nmodule.exports.getGridFSFiles = getGridFSFiles;\nmodule.exports.createGridFSReadStream = createGridFSReadStream;\n</code></pre>\n<figcaption>/database/gridfs-service.js file (Contains the GridFS driver configurations)</figcaption>\n<p>If you can see line 63, the “<em>bucketName”</em> is set to <em>“file_uploads”</em>. This means the collection that we are using for storing the files is named as <em>file_uploads</em>. After running the application if you go to the MongoDB Compass, you can see there are two new collections are created.</p>\n<pre><code>file_uploads.chunks //contains the file chunks (one file is divided in to chunks of 255 kiloBytes.\n\nfile_uploads.files //contains the metadata of the file (such as lenght, chunkSize, uploadDate, filename, md5 hash, and the contentType)\n</code></pre>\n<p>Now we need to install several packages for this. Let’s install them.</p>\n<pre><code>$ npm install multer multer-gridfs-storage gridfs-stream\n</code></pre>\n<p><em>Multer</em> is the middleware that handles <em>multipart/form-data.</em> This is a good reference if you are not familiar with them.</p>\n<p><a href=\"https://dev.to/sidthesloth92/understanding-html-form-encoding-url-encoded-and-multipart-forms-3lpa\">Understanding HTML Form Encoding: URL Encoded and Multipart Forms</a></p>\n<p>The other two packages are for the file upload handling with MongoDB GridFS.</p>\n<p>After creating this file, let’s create the GridFS middleware. It is really easy to integrate with Express since Express is handy with middleware. Let’s create <em>/middleware/gridfs-middleware.js</em> file.</p>\n<pre><code>const multer = require(\"multer\");\nconst { storage } = require(\"../database/gridfs-service\");\n\nconst upload = multer({\n  storage\n});\n\nmodule.exports = function GridFSMiddleware() {\n  return upload.single(\"image\");\n};\n</code></pre>\n<figcaption>/middleware/gridfs-middleware.js file (Contains GridFS middleware configuration)</figcaption>\n<p>There is something to mention here. If you can see line 9, I set “<em>image”</em> as the name of the form field name. You can set it to anything you like, but you have to remember it for later use. FYI, There are several methods of uploading files.</p>\n<pre><code>upload.single(\"field_name\"); //for uploading a single file\n\nupload.array(\"field_name\"); //for uploading an array of files\n\nupload.fields([{name: 'avatar'}, {name: 'gallery'}]); //for uploading an array of files with multiple field names\n\nupload.none(); //not uploading any files but contains text fields as multipart form data\n</code></pre>\n<p>Here I used, <em>upload.single(“field_name”)</em> because I want to upload only one image (Probably I’ll change this to uploading the student’s profile picture). However, the things I’ve described in the above code-block are not something I brew up myself 🤣. They are all described beautifully in the <a href=\"http://expressjs.com/en/resources/middleware/multer.html\">multer documentation</a>.</p>\n<p>Now we can set up the controller to upload files to MongoDB GridFS. Let’s update the <em>/controllers/index.js</em> file.</p>\n<pre><code>const GridFSMiddleware = require(\"../middleware/gridfs-middleware\");\n/** @route  POST /image\n *  @desc   Upload profile image\n *  @access Public\n */\nrouter.post(\n  \"/image\",\n  [GridFSMiddleware()],\n  asyncWrapper(async (req, res) => {\n    const { originalname, mimetype, id, size } = req.file;\n    res.send({ originalname, mimetype, id, size });\n  })\n);\n</code></pre>\n<p>Now let’s try to upload an image, shall we? Let’s start the web application as usual.</p>\n<pre><code>$ pm2 start\n</code></pre>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/45b4pYl4GZHQiWe9WxblCB/553d0d8387609030b2d9804a3d7c46ce/1.png\" alt=\"1\"></p>\n<figcaption>Figure 1: POST request containing the image file</figcaption>\n<p>As in figure 1, you have to select the request body as <em>form-data</em> and then you have to set the key as <em>image.</em> Now select the key type as “<em>File”</em>. (As seen in Figure 2)</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/2t0fDoUkE2J8JywdO2kCyZ/9428a97e84cfbdbc8f26715c64ffa784/2.png\" alt=\"2\"></p>\n<figcaption>Figure 2: Selecting the key type of the form data</figcaption>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/6CCuelyDU6o246w2UsmPaj/2d4ca21966ab2587e4235197e66568a3/3.png\" alt=\"3\"></p>\n<figcaption>Figure 3: Response from uploading the image to the DB</figcaption>\n<p>Now if you see the response as figure 3, it means everything worked out. Now let’s see how the MongoDB Compass shows the uploaded file.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/6pgkPIVPXI1LAfXqCbdPmf/645c70b195d2ca967646f49181d6e68c/4.png\" alt=\"4\"></p>\n<figcaption>Figure 4: file_uploads.files collection (Contains the metadata of the uploaded file)</figcaption>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/6NYYkzQvwFdDDJxpHWkp4L/f9021ff4ec7b305598c51737dc2a739f/5.png\" alt=\"5\"></p>\n<figcaption>Figure 5: file_uploads.chunks collection (Contains the file chunks of the uploaded file)</figcaption>\n<p>As you can see in figure 4, the file metadata is shown. In figure 5, you can see only one chunk. That is because the image we uploaded is less than 255kB in size.</p>\n<p>Now that we have uploaded the file, how do we view it? We cannot see the image from the DB, now can we? So let’s implement a way to view the uploaded image.</p>\n<p>Now let’s update the <em>/controllers/index.js</em> file.</p>\n<pre><code>const { getGridFSFiles } = require(\"../database/gridfs-service\");\nconst { createGridFSReadStream } = require(\"../database/gridfs-service\");\n/** @route   GET /image/:id\n *  @desc    View profile picture\n *  @access  Public\n */\nrouter.get(\n  \"/image/:id\",\n  asyncWrapper(async (req, res) => {\n    const image = await getGridFSFiles(req.params.id);\n    if (!image) {\n      res.status(404).send({ message: \"Image not found\" });\n    }\n    res.setHeader(\"content-type\", image.contentType);\n    const readStream = createGridFSReadStream(req.params.id);\n    readStream.pipe(res);\n  })\n);\n</code></pre>\n<p>What we are doing here is, we get the image id from the request and check for the image in the DB and if the image exists, we stream it. If the image is not found we return a 404 and a not found message. It is as simple as that.</p>\n<p>Now let’s try that out.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/2lukIvJLSTA2INPEdC8otE/acf511e666a7ff919beff9a77c849ac8/6.png\" alt=\"6\"></p>\n<figcaption>Figure 6: GET request to view the image.</figcaption>\n<p>Remember the image id is what gets returned as the <em>id</em> in figure 3.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/1VSOUt227XHRgFidcLPK0t/3064f7da35f20465d38de46cbbe837b2/7.png\" alt=\"7\"></p>\n<figcaption>Figure 7: Image is streamed (Image is from [https://nodejs.org/en/about/resources/](https://nodejs.org/en/about/resources/))</figcaption>\n<p>If we send the GET request from a web browser, we’ll see the image in the browser. (If you get a “<em>Your connection is not private”</em> message, ignore it.) It will be the same as in figure 7.</p>\n<p>So that was a lot of work, isn’t it? But totally worth it. Now you can save your precious images inside a MongoDB database and view them from a browser. Go show off that talent to your friends and impress them 😁.</p>\n<p>This is the full <em>/controllers/index.js</em> file for your reference.</p>\n<pre><code>/controllers/index.js file (Updated to reflect the view and upload image endpoints)\n</code></pre>\n<p>So, this is the end for this tutorial and in the next tutorial, I will tell you how to create and use custom middleware with Express. (Remember I told you Express is great with middleware). As usual, you can see the whole code behind this tutorial in my GitHub repository. (Check for the commit message “Tutorial 4 checkpoint”.)</p>\n<p><a href=\"https://github.com/Niweera/node-is-simple\">Node is Simple</a></p>\n<p>So until we meet again, happy coding…</p>"}},"categories":[{"name":"How To","slug":"how-to"},{"name":"Tutorials","slug":"tutorials"}]}},{"node":{"slug":"node-is-simple-part-3","title":"Node Is Simple — Part 3","image":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/4aqJ0ZocLa8mpss27qmc45/e1b04775669dbc86532c8505d3a0da55/3.png","fileName":"3.png"}},"bodyContent":{"childMarkdownRemark":{"html":"<p><strong><em>tl;dr</em></strong> — <em>This is the third article of the</em> <strong><em>Node is Simple</em></strong> <em>article series. In this article series, I will be discussing how to create a simple and secure NodeJS, Express, MongoDB web application.</em></p>\n<p>To follow the past tutorials, <a href=\"https://node.dev/post/node-is-simple-part-1\">Node is Simple Part 1</a>, and <a href=\"https://node.dev/post/node-is-simple-part-2\">Node is Simple Part 2</a>.</p>\n<p>Hello, fellow developers, I am once again, asking you to learn some NodeJS with me. In this tutorial, I will be discussing creating basic CRUD operations in NodeJS. So without further ado, let’s start, shall we?</p>\n<h2>CREATE endpoint</h2>\n<p>If you can remember in my <a href=\"https://medium.com/@niweera/node-is-simple-part-2-b888294a00b8\">previous article</a>, I have created a simple endpoint to POST a name and city of a student and created a record (document) of the student. What I am going to do is enhance what I’ve already done. Let’s update the model, and the service to reflect our needs.</p>\n<p>We are going to add some new fields to the student document.</p>\n<pre><code>const mongoose = require(\"../database\");\nconst Schema = mongoose.Schema;\n\nconst studentSchema = new Schema(\n  {\n    _id: {\n      type: mongoose.SchemaTypes.String,\n      unique: true,\n      required: true,\n      index: true\n    },\n    name: { type: mongoose.SchemaTypes.String, required: true },\n    city: { type: mongoose.SchemaTypes.String, required: true },\n    telephone: { type: mongoose.SchemaTypes.Number, required: true },\n    birthday: { type: mongoose.SchemaTypes.Date, required: true }\n  },\n  { strict: true, timestamps: true, _id: false }\n);\n\nconst collectionName = \"student\";\n\nconst Student = mongoose.model(collectionName, studentSchema, collectionName);\n\nmodule.exports = {\n  Student\n};\n</code></pre>\n<figcaption>Updated /models/index.js file</figcaption>\n<p>What I’ve done here is added <em>\\</em>id, telephone,_ and <em>birthday</em> as the new fields. And I have disabled the Mongoose default <em>\\</em>id_ and specified my own.</p>\n<p>Now let’s update the service file.</p>\n<pre><code>const { Student } = require(\"../models\");\n\nmodule.exports = class StudentService {\n  async registerStudent(data) {\n    const { _id, name, city, telephone, birthday } = data;\n\n    const new_student = new Student({\n      _id,\n      name,\n      city,\n      telephone,\n      birthday\n    });\n\n    const response = await new_student.save();\n    const res = response.toJSON();\n    delete res.__v;\n    return res;\n  }\n};\n</code></pre>\n<figcaption>Updated /services/index.js file</figcaption>\n<p>Before we are going to test what we have done, I am going to let you in on a super-secret. If you have experience in developing NodeJS applications, I hope you have come across the <a href=\"https://nodemon.io/\">Nodemon</a> tool. It restarts the server once you changed the files. But today I am going to tell you about this amazing tool called <a href=\"https://pm2.keymetrics.io/\">PM2</a>.</p>\n<h2>What is PM2?</h2>\n<p>PM2 is a production-grade process management tool. It has various capabilities such as load balancing (which I will discuss in a later tutorial), enhanced logging features, adding environment variables, and many more. Their <a href=\"https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/\">documentation</a> is super nifty and worth checking out.</p>\n<p>So let’s install PM2 and start using it in our web app.</p>\n<pre><code>$ npm install pm2@latest -g\n</code></pre>\n<p>Let’s create <em>ecosystem.config.js</em> file in the project root, which will contain all of our environment variables, keys, secrets, and PM2 configurations.</p>\n<pre><code>const fs = require(\"fs\");\n\nconst SERVER_CERT = fs.readFileSync(__dirname + \"/config/server.cert\", \"utf8\");\nconst SERVER_KEY = fs.readFileSync(__dirname + \"/config/server.key\", \"utf8\");\n\nmodule.exports = {\n  apps: [\n    {\n      name: \"node-is-simple\",\n      script: \"./index.js\",\n      watch: true,\n      env: {\n        NODE_ENV: \"development\",\n        SERVER_CERT,\n        SERVER_KEY,\n        HTTP_PORT: 8080,\n        HTTPS_PORT: 8081,\n        MONGO_URI: \"mongodb://localhost/students\"\n      }\n    }\n  ]\n};\n</code></pre>\n<figcaption>ecosystem.config.js file (The configuration file for PM2)</figcaption>\n<p>Since we have moved all of our keys as the environment variables, now we have to change <em>/config/index.js</em> file to reflect these changes.</p>\n<pre><code>module.exports = {\n  SERVER_CERT: process.env.SERVER_CERT,\n  SERVER_KEY: process.env.SERVER_KEY,\n  HTTP_PORT: process.env.HTTP_PORT,\n  HTTPS_PORT: process.env.HTTPS_PORT,\n  MONGO_URI: process.env.MONGO_URI\n};\n</code></pre>\n<figcaption>Updated /config/index.js file (here we have moved all the secrets to the ecosystem.config.js file as environment variables)</figcaption>\n<p>Now, remember, <em>/config/index.js</em> is safe to commit to a public repository. But not the <em>ecosystem.config.js</em> file. Also never commit your private keys to a public repository (But I’ve done it for the demonstration purposes). Protect your secrets like your cash 😂.</p>\n<p>Since we have done our initial setup let’s run our application. And one thing to keep in mind. If you start the application, as usual,</p>\n<pre><code>$ node index.js\n</code></pre>\n<p>it won’t work. Now we have to use PM2 to start our application because it contains all the environment variables needed for the Node web application. Now go to the project root folder and run the following command.</p>\n<pre><code>$ pm2 start\n</code></pre>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/2dYMwtqTUEhanvPiFRDrvF/c3feab36eb6d19e4b95e150ee7fdfc0b/1.png\" alt=\"1\"></p>\n<figcaption>Figure 1: PM2 startup</figcaption>\n<p>If you see this (figure 1) in your console it is working as it should. Now to see the logs run the following command.</p>\n<pre><code>$ pm2 logs\n</code></pre>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/5550cNdtrp8croBKu9xRQy/6b37778d92facccf4b73c52f0877e571/2.png\" alt=\"2\"></p>\n<figcaption>Figure 2: PM2 logs</figcaption>\n<p>If you see this (figure 2) in your console then the node app is working as it should.</p>\n<h2>Enough with the PM2</h2>\n<p>Yes, let’s move to test our enhanced CREATE endpoint.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/5xaxjOeH89dfwvATgk5z4E/17167a02aa03f7720c88c883ed74e6de/3.png\" alt=\"3\"></p>\n<figcaption>Figure 3: POST request in Postman</figcaption>\n<p>Now create a request like this (figure 3) and hit Send.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/2GCkcYOXS4gP5SpEWmavuh/f463273ae5546aff8581e7671a2657b8/4.png\" alt=\"4\"></p>\n<figcaption>Figure 4: POST response in Postman</figcaption>\n<p>If you see this response (figure 4), it is safe to say everything works as it should. Yay!</p>\n<p>Now since we have a CREATE endpoint, let’s add a READ endpoint.</p>\n<h2>READ endpoint</h2>\n<p>Now let’s read what’s inside our <em>student</em> collection. We can view all the students who are registered, or we can see details from only one student.</p>\n<p><em>GET /students</em></p>\n<p>Now let’s get all the students’ details. We only get the <em>\\</em>id, name,_ and <em>city</em> of the student here. Add these lines to the <em>/controllers/index.js</em> file.</p>\n<pre><code>/** @route  GET /students\n *  @desc   Get all students\n *  @access Public\n */\nrouter.get(\n  \"/students\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.getAllStudents();\n    res.send(response);\n  })\n);\n</code></pre>\n<p>And add these lines (inside the <em>StudentService</em> class) to the <em>/servcies/index.js</em> file.</p>\n<pre><code>_async_ getAllStudents() {  \n  _return_ Student.find({}, \"\\_id name city\");  \n}\n</code></pre>\n<p>Let me give a summary of the above lines. <em>Student.find()</em> is the method to apply queries to the MongoDB. Since we need all the students we pass the empty object as the first argument. As the second argument (which is called a projection) we provide the fields we want to return and the fields we do not want to return. Here I want <em>\\</em>id, name,_ and <em>city.</em> We can use “-<em>field\\</em>name”_ to provide the field we do not want.</p>\n<p>GET <em>/students/:id</em></p>\n<p>Now let’s get all the details from a single student. Now here we are getting all the details of a single student.</p>\n<p>Now add these lines to the <em>/controllers/index.js</em> file.</p>\n<pre><code>/** @route  GET /students/:id\n *  @desc   Get a single student\n *  @access Public\n */\nrouter.get(\n  \"/students/:id\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.getStudent(req.params.id);\n    res.send(response);\n  })\n);\n</code></pre>\n<p>In the <em>Express</em> router, we can specify a path parameter via /:<em>param</em> syntax. Now we can access this path parameter via <em>req.params.param.</em> This is basic <em>Express</em> and to get more knowledge on this please refer to the <a href=\"https://expressjs.com/en/guide/routing.html\">documentation</a>, and it is a great source of good knowledge.</p>\n<p>Now add these lines to the <em>/servcies/index.js</em> file.</p>\n<pre><code>_async_ getStudent(\\_id) {  \n  _return_ Student.findById(\\_id, \"-\\_\\_v -createdAt -updatedAt\");  \n}\n</code></pre>\n<p>Here we provide the <em>\\</em>id_ of the student to get the details. As the projection, we do not want <em>\\</em>_v, createdAt,_ and <em>updatedAt</em> fields.</p>\n<p>Now let’s check these endpoints.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/Jyk58isjAqmuywwLoUlLg/6162552a6d18bd48975c28ca1c013fd4/5.png\" alt=\"5\"></p>\n<figcaption>Figure 5: Request /students</figcaption>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/3gJtTxSNhH0BgqAfg6k9CB/8aa7411bdfaafe2f032305d76378ab85/6.png\" alt=\"6\"></p>\n<figcaption>Figure 6: Response /students</figcaption>\n<p>I have added two more students’ details, so I got three records.</p>\n<p>Now let’s check the single student endpoint.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/3afY8PPNez6lHxv74BA6aG/43d5332068c4d61cb8fca9fd7148fa5c/7.png\" alt=\"7\"></p>\n<figcaption>Figure 7: Request /students/stud\\_1</figcaption>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/5oIO1gQYP7Ljo0XigUpuTP/c132236e231e5f6121bf2cc35ca6ac85/8.png\" alt=\"8\"></p>\n<figcaption>Figure 8: Response /students/stud\\_1</figcaption>\n<p>If you get similar results in figure 6 and figure 8 let’s say it was a success.</p>\n<h2>Update endpoint</h2>\n<p>Since we created student records, viewed these student records, now it is time to update these student records.</p>\n<p>To PUT, or to PATCH?</p>\n<p>So this is the biggest question, to update a resource, should we use PUT or PATCH? The answer is somewhat simple. If you want to update the whole resource every time, use PUT. If you want to update the resource partially, use PATCH. It is that simple. This article clarified this dilemma.</p>\n<p><a href=\"https://rapidapi.com/blog/put-vs-patch/#:~:text=The%20main%20difference%20between%20PUT,identified%20by%20the%20Request%2DURI.&#x26;text=On%20the%20other%20hand%2C%20HTTP,on%20where%20it%20is%20implemented.\">Differences between PUT and PATCH</a></p>\n<p>Since I am going to partially update the student record, I will be using PATCH.</p>\n<p>PATCH /students/:id</p>\n<p>Now let’s update the <em>/controllers/index.js</em> file.</p>\n<pre><code>/** @route  PATCH /students/:id\n *  @desc   Update a single student\n *  @access Public\n */\nrouter.patch(\n  \"/students/:id\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.updateStudent(\n      req.params.id,\n      req.body\n    );\n    res.send(response);\n  })\n);\n</code></pre>\n<p>After adding this let’s update the <em>/services/index.js</em> file.</p>\n<pre><code>_async_ updateStudent(\\_id, { name, city, telephone, birthday }) {  \n  _return_ Student.findOneAndUpdate(  \n    { \\_id },  \n    {  \n      name,  \n      city,  \n      telephone,  \n      birthday  \n    },  \n    {  \n      _new_: _true_,  \n      omitUndefined: _true_,  \n      fields: \"-\\_\\_v -createdAt -updatedAt\"  \n    }  \n  );  \n}\n</code></pre>\n<p>Let me give a brief description of what’s going on here. We update the student by the given id, and we provide the <em>name, city, telephone,</em> and <em>birthday</em> data to be updated. As the third argument we provide <em>new: true</em> to return the updated document to us, <em>omitUndefined: true</em> to partially update the resource and <em>fields: “-\\</em>_v -createdAt -updatedAt”_ to remove these fields from the returning document.</p>\n<p>Now let’s check this out.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/6loAbeATuw2yemdNDaFsVj/3cb60b51c4b05407c28457b6bb2a745a/9.png\" alt=\"9\"></p>\n<figcaption>Figure 9: Updating the name of the student (stud\\_1)</figcaption>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/3XVaKIJh9CaiaTEsvx9mLQ/0acdb54e1422b92fc2ec71bae0c081f8/10.png\" alt=\"10\"></p>\n<figcaption>Figure 10: The student’s name has changed from June to Jane</figcaption>\n<p>So if you get similar results as figure 10 then let’s say yay! Now let’s move on to the final part of this tutorial, which is DELETE.</p>\n<h2>DELETE endpoint</h2>\n<p>Since we create, read, and update, now it is time to delete some students 😁.</p>\n<p>DELETE /students/:id</p>\n<p>Since we should not delete all the students at once (It is a best practice IMO), let’s delete student by the provided student_id.</p>\n<p>Now let’s update the <em>/controllers/index.js</em> file.</p>\n<pre><code>/** @route  DELETE /students/:id\n *  @desc   Delete a single student\n *  @access Public\n */\nrouter.delete(\n  \"/students/:id\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.deleteStudent(req.params.id);\n    res.send(response);\n  })\n);\n</code></pre>\n<p>Now let’s update the <em>/services/index.js</em> file.</p>\n<pre><code>_async_ deleteStudent(\\_id) {  \n  _await_ Student.deleteOne({ \\_id });  \n  _return_ { message: \\`Student \\[${\\_id}\\] deleted successfully\\` };  \n}\n</code></pre>\n<p>Now the time to see this in action.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/51lF4tszuB1GSkvJuOiszw/b77e1d78af7674ec28f747a32d5a5f33/11.png\" alt=\"11\"></p>\n<figcaption>Figure 11: Request to delete student with stdent\\_id \\[stud\\_2\\]</figcaption>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/2GDAjO0sLtucU0Juii1wxL/79583b63a0c0d1b4c1a856af148e0f58/12.png\" alt=\"12\"></p>\n<figcaption>Figure 12: Response of deleting student with stdent\\_id \\[stud\\_2\\]</figcaption>\n<p>If the results are similar to figure 12, then it is safe to assume, the application works as it should.</p>\n<p>So here are the current <em>/controllers/index.js</em> file and <em>/services/index.js</em> file for your reference.</p>\n<pre><code>const router = require(\"express\").Router();\nconst asyncWrapper = require(\"../utilities/async-wrapper\");\nconst StudentService = require(\"../services\");\nconst studentService = new StudentService();\n\n/** @route  GET /\n *  @desc   Root endpoint\n *  @access Public\n */\nrouter.get(\n  \"/\",\n  asyncWrapper(async (req, res) => {\n    res.send({\n      message: \"Hello World!\",\n      status: 200\n    });\n  })\n);\n\n/** @route  POST /register\n *  @desc   Register a student\n *  @access Public\n */\nrouter.post(\n  \"/register\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.registerStudent(req.body);\n    res.send(response);\n  })\n);\n\n/** @route  GET /students\n *  @desc   Get all students\n *  @access Public\n */\nrouter.get(\n  \"/students\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.getAllStudents();\n    res.send(response);\n  })\n);\n\n/** @route  GET /students/:id\n *  @desc   Get a single student\n *  @access Public\n */\nrouter.get(\n  \"/students/:id\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.getStudent(req.params.id);\n    res.send(response);\n  })\n);\n\n/** @route  PATCH /students/:id\n *  @desc   Update a single student\n *  @access Public\n */\nrouter.patch(\n  \"/students/:id\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.updateStudent(\n      req.params.id,\n      req.body\n    );\n    res.send(response);\n  })\n);\n\n/** @route  DELETE /students/:id\n *  @desc   Delete a single student\n *  @access Public\n */\nrouter.delete(\n  \"/students/:id\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.deleteStudent(req.params.id);\n    res.send(response);\n  })\n);\n\nmodule.exports = router;\n</code></pre>\n<figcaption>Updated /controllers/index.js file (contains CRUD endpoints)</figcaption>\n<pre><code>const { Student } = require(\"../models\");\n\nmodule.exports = class StudentService {\n  async registerStudent(data) {\n    const { _id, name, city, telephone, birthday } = data;\n\n    const new_student = new Student({\n      _id,\n      name,\n      city,\n      telephone,\n      birthday\n    });\n\n    const response = await new_student.save();\n    const res = response.toJSON();\n    delete res.__v;\n    return res;\n  }\n\n  async getAllStudents() {\n    return Student.find({}, \"_id name city\");\n  }\n\n  async getStudent(_id) {\n    return Student.findById(_id, \"-__v -createdAt -updatedAt\");\n  }\n\n  async updateStudent(_id, { name, city, telephone, birthday }) {\n    return Student.findOneAndUpdate(\n      { _id },\n      {\n        name,\n        city,\n        telephone,\n        birthday\n      },\n      {\n        new: true,\n        omitUndefined: true,\n        fields: \"-__v -createdAt -updatedAt\"\n      }\n    );\n  }\n\n  async deleteStudent(_id) {\n    await Student.deleteOne({ _id });\n    return { message: `Student [${_id}] deleted successfully` };\n  }\n};\n</code></pre>\n<figcaption>Updated /services/index.js file (Contains all CRUD endpoints)</figcaption>\n<p>So this is it for this tutorial, and we will meet again in a future tutorial about uploading files to MongoDB using GridFS. As usual, you can find the code here (Check for the commit message <em>“Tutorial 3 checkpoint”</em>).</p>\n<p><a href=\"https://github.com/Niweera/node-is-simple\">node-is-simple</a></p>\n<p>So until we meet again, happy coding…</p>"}},"categories":[{"name":"How To","slug":"how-to"},{"name":"Tutorials","slug":"tutorials"}]}},{"node":{"slug":"node-is-simple-part-2","title":"Node Is Simple — Part 2","image":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/H0hK6NW9d5IUfT0boXBBc/b7b2052395c92ae841256065a5566286/node_is_simple.png","fileName":"node_is_simple.png"}},"bodyContent":{"childMarkdownRemark":{"html":"<p><strong><em>tl;dr</em></strong> — <em>This is the second article of the</em> <strong><em>Node is Simple</em></strong> <em>article series. In this article series, I will be discussing how to create a simple and secure NodeJS, Express, MongoDB web application.</em></p>\n<p>Hello, my friends, this is part two of <strong>Node is Simple</strong> article series, where I will be discussing how to add MongoDB to your web application. If you haven’t read my first article you can read it from here: <a href=\"https://node.dev/post/node-is-simple-part-1\">Node is Simple - Part 1</a></p>\n<hr>\n<h2>So what is <a href=\"https://www.mongodb.com/\">MongoDB</a>?</h2>\n<p>If you haven’t heard of MongoDB that is news to me. It is the most popular database for modern web applications. (Yeah, yeah, <a href=\"https://firebase.google.com/\">Firebase</a>, <a href=\"https://firebase.google.com/docs/firestore\">Firestore</a> are there too.) MongoDB is a NoSQL database where it has documents as the atomic data structure and a collection of documents is a <strong>Collection.</strong> With these documents and collections, we can store data as we want.</p>\n<pre><code>{     \n \"\\_id\": \"5cf0029caff5056591b0ce7d\",     \n \"firstname\": \"Jane\",     \n \"lastname\": \"Wu\",     \n \"address\": {       \n     \"street\": \"1 Circle Rd\",       \n     \"city\": \"Los Angeles\",       \n     \"state\": \"CA\",       \n     \"zip\": \"90404\"     \n },     \n \"hobbies\": \\[\"surfing\", \"coding\"\\]   \n}\n</code></pre>\n<p>This is how a simple document is constructed in MongoDB. For our tutorial, we will use <a href=\"https://www.mongodb.com/cloud/atlas\">MongoDB Cloud Atlas</a> which is a MongoDB server as a service platform. I am not going to explain how to create an Atlas account and set up a database since it is really easy and the following is a really good reference.</p>\n<p><a href=\"https://towardsdatascience.com/getting-started-with-mongodb-atlas-overview-and-tutorial-7a1d58222521\">Getting Started with MongoDB Atlas: Overview and Tutorial</a></p>\n<p>After creating the MongoDB account and set up the database obtain the MongoDB URI which looks like this.</p>\n<pre><code>**_mongodb+srv://your\\_user\\_name:your\\_password@cluster0-v6q0g.mongodb.net/database\\_name_**\n</code></pre>\n<p>You can specify the following with the URI.</p>\n<p><em>your\\</em>user_name:_ The username of the MongoDB database</p>\n<p><em>your\\</em>password:_ The password for the MongoDB database</p>\n<p><em>database\\</em>name:_ The MongoDB database name</p>\n<p>Now that you have the MongoDB URI, you can use <a href=\"https://www.mongodb.com/products/compass\">MongoDB Compass</a> to view the database and create new collections.</p>\n<h2>Now let’s move on to the coding, shall we?</h2>\n<p>First of all, let me tell you something awesome about linting. To catch errors in your code, before running any tests, it is vital to do linting. In linting, tools like ESLint, look at your code and displays warnings and errors about your code. So let’s set up ESLint in your development environment.</p>\n<ol>\n<li>Setting up ESLint in VSCode</li>\n</ol>\n<p>This is a good reference to setting up ESLint in VSCode: <a href=\"https://www.digitalocean.com/community/tutorials/linting-and-formatting-with-eslint-in-vs-code\">Linting and Formatting with ESLint in VS Code</a></p>\n<ol start=\"2\">\n<li>Setting up <a href=\"https://www.npmjs.com/package/eslint\">ESLint</a> in WebStorm</li>\n</ol>\n<p>First, install ESLint in your project path.</p>\n<pre><code>$ npm install eslint --save-dev\n</code></pre>\n<p>There are several ESLint configurations to use. Let’s create <em>.eslintrc.json</em> file in the project root folder and specify the configurations.</p>\n<pre><code>{\n  \"env\": {\n    \"browser\": true,\n    \"commonjs\": true,\n    \"es6\": true,\n    \"node\": true\n  },\n  \"extends\": [\"eslint:recommended\"],\n  \"globals\": {\n    \"Atomics\": \"readonly\",\n    \"SharedArrayBuffer\": \"readonly\"\n  },\n  \"parserOptions\": {\n    \"ecmaVersion\": 2018\n  },\n  \"rules\": {}\n}\n</code></pre>\n<figcaption>_.eslintrc.json file (The configuration file for ESLint)_</figcaption>\n<p>After that go to settings in WebStorm and then select <em>Manual ESLint configuration</em>.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/5F4OK4WRvLzo5MSP0KORs1/3e25487a9cd93709f0dc337fc3e1500f/1.png\" alt=\"1\"></p>\n<figcaption>ESLint configuration settings on WebStorm</figcaption>\n<p>Then click <em>OK</em> and done and dusted.</p>\n<h2>Show me the Code!!!</h2>\n<p>Alright, alright, let’s move on to the real deal. Now we are going to create a <a href=\"https://mongoosejs.com/\">Mongoose</a> reference for the MongoDB database and create some models. Mongoose is the Object Document Model for the MongoDB in NodeJS environment. It is really easy to use and the <a href=\"https://mongoosejs.com/docs/guide.html\">documentation</a> is really good. Let me tell you a super-secret. Read the documentation, always read the documentation. Documentation is your best friend. 🤣</p>\n<p>So first let's install the mongoose package inside the project folder.</p>\n<pre><code>$ npm install mongoose --save\n</code></pre>\n<p>Now let’s create the database connection file <em>index.js</em> in <em>/database</em> folder.</p>\n<pre><code>const mongoose = require(\"mongoose\");\nconst config = require(\"../config\");\nconst dbPath = config.MONGO_URI;\nconst chalk = require(\"chalk\");\n\nmongoose\n  .connect(dbPath, {\n    useNewUrlParser: true,\n    useUnifiedTopology: true,\n    useCreateIndex: true,\n    useFindAndModify: false\n  })\n  .then(() => {\n    console.log(chalk.yellow(\"[!] Successfully connected to the database\"));\n  })\n  .catch(err => {\n    console.log(chalk.red(err.message));\n  });\n\nconst db = mongoose.connection;\n\ndb.on(\"error\", () => {\n  console.log(chalk.red(\"[-] Error occurred from the database\"));\n});\n\ndb.once(\"open\", () => {\n  console.log(\n    chalk.yellow(\"[!] Successfully opened connection to the database\")\n  );\n});\n\nmodule.exports = mongoose;\n</code></pre>\n<figcaption>/database/index.js file (Contains MongoDB configurations)</figcaption>\n<p>Now let’s update the /<em>config/index.js</em> file.</p>\n<pre><code>const fs = require(\"fs\");\n\nconst SERVER_CERT = fs.readFileSync(__dirname + \"/server.cert\", \"utf8\");\nconst SERVER_KEY = fs.readFileSync(__dirname + \"/server.key\", \"utf8\");\n\nmodule.exports = {\n  SERVER_CERT,\n  SERVER_KEY,\n  HTTP_PORT: 8080,\n  HTTPS_PORT: 8081,\n  MONGO_URI:\n    \"mongodb+srv://your_user_name:your_password@cluster0-v6q0g.mongodb.net/students\"\n};\n</code></pre>\n<figcaption>/config/index.js file (Contains configurations of the project)</figcaption>\n<p>Remember to change the MONGO_URI according to the one you obtained from MongoDB Cloud Atlas instance.</p>\n<p>Now let’s create a simple mongoose model. Create <em>index.js</em> inside <em>/models</em> folder.</p>\n<pre><code>const mongoose = require(\"../database\");\nconst Schema = mongoose.Schema;\n\nconst studentSchema = new Schema(\n  {\n    name: { type: mongoose.SchemaTypes.String },\n    city: { type: mongoose.SchemaTypes.String }\n  },\n  { strict: true, timestamps: true }\n);\n\nconst collectionName = \"student\";\n\nconst Student = mongoose.model(collectionName, studentSchema, collectionName);\n\nmodule.exports = {\n  Student\n};\n</code></pre>\n<figcaption>/models/index.js file (Contains Mongoose model schemas)</figcaption>\n<p>As simple as that. Now let’s create a simple service to create a student using the endpoint. Create <em>index.js</em> file inside <em>/services</em> folder.</p>\n<pre><code>const { Student } = require(\"../models\");\n\nmodule.exports = class StudentService {\n  async registerStudent(data) {\n    const { name, city } = data;\n\n    const new_student = new Student({\n      name,\n      city\n    });\n\n    const response = await new_student.save();\n    const res = response.toJSON();\n    delete res.__v;\n    return res;\n  }\n};\n</code></pre>\n<figcaption>/services/index.js file</figcaption>\n<p>Simple right? Now let’s use this service inside a controller. Remember our controller, we created in the first article. Let’s update it.</p>\n<pre><code>const router = require(\"express\").Router();\nconst asyncWrapper = require(\"../utilities/async-wrapper\");\nconst StudentService = require(\"../services\");\nconst studentService = new StudentService();\n\n/** @route  GET /\n *  @desc   Root endpoint\n *  @access Public\n */\nrouter.get(\n  \"/\",\n  asyncWrapper(async (req, res) => {\n    res.send({\n      message: \"Hello World!\",\n      status: 200\n    });\n  })\n);\n\n/** @route  POST /register\n *  @desc   Register a student\n *  @access Public\n */\nrouter.post(\n  \"/register\",\n  asyncWrapper(async (req, res) => {\n    const response = await studentService.registerStudent(req.body);\n    res.send(response);\n  })\n);\n\nmodule.exports = router;\n</code></pre>\n<figcaption>/controllers/index.js file (Contains Express Router to handle requests)</figcaption>\n<p>It’s not over yet. If you run this application as of now and send a POST request to the <em>/register</em> endpoint, it would just return a big error message. It is because our application still doesn’t know how to parse a JSON payload. It would just complain that <em>req.body</em> is undefined. So let’s teach how to parse a JSON payload to our web application. It is not much but it’s honest work. We have to use a simple Express middleware called <a href=\"https://www.npmjs.com/package/body-parser\">Body-Parser</a> for this situation. Now let’s set up this.</p>\n<p>First, install the following packages inside the project folder.</p>\n<pre><code>$ npm install body-parser helmet --save\n</code></pre>\n<p>Create the file <em>common.js</em> inside <em>/middleware</em> folder.</p>\n<pre><code>const bodyParser = require(\"body-parser\");\nconst helmet = require(\"helmet\");\n\nmodule.exports = app => {\n  app.use(bodyParser.json());\n  app.use(helmet());\n};\n</code></pre>\n<figcaption>/middleware/common.js file (Contains all the common middleware for the Express app)</figcaption>\n<p><a href=\"http://expressjs.com/en/resources/middleware/body-parser.html\">Body-Parser</a> is the middleware which parses the body payload. And <a href=\"https://www.npmjs.com/package/helmet\">Helmet</a> is there to secure your web application by setting various security HTTP headers.</p>\n<p>After that let’s export our middleware as a combined middleware. Now if we want to add new middleware all we have to do is update the <em>common.js</em> file. Create <em>index.js</em> file inside <em>/middleware</em> folder.</p>\n<pre><code>const CommonMiddleware = require(\"./common\");\n\nconst Middleware = app => {\n  CommonMiddleware(app);\n};\n\nmodule.exports = Middleware;\n</code></pre>\n<figcaption>/middleware/index.js file (Exports all the common middleware)</figcaption>\n<p>We are not done yet. Now we have to include this main middleware file inside the <em>index.js</em> root file. Remember we created the <em>index.js</em> file inside the project root folder. Let’s update it.</p>\n<pre><code>const express = require(\"express\");\nconst chalk = require(\"chalk\");\nconst http = require(\"http\");\nconst https = require(\"https\");\nconst config = require(\"./config\");\n\nconst HTTP_PORT = config.HTTP_PORT;\nconst HTTPS_PORT = config.HTTPS_PORT;\nconst SERVER_CERT = config.SERVER_CERT;\nconst SERVER_KEY = config.SERVER_KEY;\n\nconst app = express();\nconst Middleware = require(\"./middleware\");\nconst MainController = require(\"./controllers\");\n\nMiddleware(app);\napp.use(\"\", MainController);\napp.set(\"port\", HTTPS_PORT);\n\n/**\n * Create HTTPS Server\n */\n\nconst server = https.createServer(\n  {\n    key: SERVER_KEY,\n    cert: SERVER_CERT\n  },\n  app\n);\n\nconst onError = error => {\n  if (error.syscall !== \"listen\") {\n    throw error;\n  }\n\n  const bind =\n    typeof HTTPS_PORT === \"string\"\n      ? \"Pipe \" + HTTPS_PORT\n      : \"Port \" + HTTPS_PORT;\n\n  switch (error.code) {\n    case \"EACCES\":\n      console.error(chalk.red(`[-] ${bind} requires elevated privileges`));\n      process.exit(1);\n      break;\n    case \"EADDRINUSE\":\n      console.error(chalk.red(`[-] ${bind} is already in use`));\n      process.exit(1);\n      break;\n    default:\n      throw error;\n  }\n};\n\nconst onListening = () => {\n  const addr = server.address();\n  const bind = typeof addr === \"string\" ? `pipe ${addr}` : `port ${addr.port}`;\n  console.log(chalk.yellow(`[!] Listening on HTTPS ${bind}`));\n};\n\nserver.listen(HTTPS_PORT);\nserver.on(\"error\", onError);\nserver.on(\"listening\", onListening);\n\n/**\n * Create HTTP Server (HTTP requests will be 301 redirected to HTTPS)\n */\nhttp\n  .createServer((req, res) => {\n    res.writeHead(301, {\n      Location:\n        \"https://\" +\n        req.headers[\"host\"].replace(\n          HTTP_PORT.toString(),\n          HTTPS_PORT.toString()\n        ) +\n        req.url\n    });\n    res.end();\n  })\n  .listen(HTTP_PORT)\n  .on(\"error\", onError)\n  .on(\"listening\", () =>\n    console.log(chalk.yellow(`[!] Listening on HTTP port ${HTTP_PORT}`))\n  );\n\nmodule.exports = app;\n</code></pre>\n<figcaption>/index.js file (Contains the Express app configuration)</figcaption>\n<p>Well done people, now we have completed setting up MongoDB connection and the model. So how do we test this? It is so simple, we just have to use a super easy tool called <a href=\"https://www.postman.com/\">Postman</a>.</p>\n<h2>Testing API endpoints with Postman</h2>\n<p>I hope you all know what Postman does. (Not the one that delivers letters ofc.) Install Postman and fire it up.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/ZGIz9cvXhxHGF1WtHq4LJ/63d6a71a9b3a2ec89f72e3f1c18a9af1/2.jpeg\" alt=\"2\"><img src=\"//images.ctfassets.net/xmu5vdhtphau/7zNST0cSgnmnwVk4Jn6Man/a9e0f9ddae9a43383613c8118a6b9398/2.jpeg\" alt=\"2\"></p>\n<figcaption>Figure 1: Postman Settings</figcaption>\n<p>As in figure 1, change the settings for SSL certificate validation. And set it to off. Since we only have a self-signed SSL certificate. (Remember tutorial one.) After that, we are ready to go.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/2CgEc5YjKwYItNch6N3Wmo/32e7d00851dba90eb11fa609cdcd6ef5/3.png\" alt=\"3\"></p>\n<figcaption>Figure 2: Request creation in Postman</figcaption>\n<p>As in figure 2, create your JSON body request. Add your name and city. Then click Send.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/7wa5ISuyFy6NzFWWnfaoBV/f088c7699a69aca595464143fb629f57/4.png\" alt=\"4\"></p>\n<figcaption>Figure 3: Response to the request</figcaption>\n<p>If everything goes as it should, you’ll see this response. If you see this response, voila, everything works correctly. Now let’s take a look at MongoDB Compass.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/6JQEbHhxzEzr5l06wDPPdp/8f3e7f731a6f8b8ec212f9763c3ac1a1/5.png\" alt=\"5\"></p>\n<figcaption>Figure 4: MongoDB Compass view</figcaption>\n<p>As in figure 3, you'll see how it shows in the database. Here, the MongoDB database is “<em>students”</em> and the collection is “<em>student”</em> and the document is the one that is showed in the view.</p>\n<p>Now that was easy right? So that’s it for this tutorial. In the coming tutorial, I’ll add some more CRUD operations to give you more details on working with MongoDB. All the code is saved in the GitHub repo and matched with the commit message. Look for the commit message “Tutorial 2 checkpoint”.</p>\n<p><a href=\"https://github.com/Niweera/node-is-simple\">Niweera/node-is-simple</a></p>\n<p>Until we meet again, happy coding…</p>"}},"categories":[{"name":"How To","slug":"how-to"},{"name":"Tutorials","slug":"tutorials"}]}},{"node":{"slug":"node-is-simple-part-1","title":"Node is Simple — Part 1","image":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/1wPDiEeSUpjD3lRRdev6UP/fa2b5a348289eb756540991b919747db/1_q4C3LGm0jGTaDtoSco5d1w.jpg","fileName":"1_q4C3LGm0jGTaDtoSco5d1w.jpg"}},"bodyContent":{"childMarkdownRemark":{"html":"<p><strong><em>tl;dr</em></strong> — <em>This is the first article of the</em> <strong><em>Node is Simple</em></strong> <em>article series. In this article series, I will be discussing how to create a simple and secure NodeJS, Express, MongoDB web application.</em></p>\n<p>First of all let me give a big shout out to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript\">JavaScript</a>, who’s going to turn 25 years old this year. W/O JavaScript, the world would be a much darker place indeed. 😁 In this article series what I am going to do is create an API with <a href=\"https://nodejs.org/\">NodeJS</a>, <a href=\"http://expressjs.com/\">ExpressJS</a>, and <a href=\"https://www.mongodb.com/\">MongoDB</a>. I know there is a vast ocean of tutorials out there, describing how to build an API with these technologies, but the thing is that I have never found a very comprehensive all in one tutorial where you get the knowledge of the following things.</p>\n<ol>\n<li>Setting up a basic NodeJS, Express web app with SSL/TLS.</li>\n<li>Setting up <a href=\"https://eslint.org/\">ESLint</a> in your favorite editor or IDE.</li>\n<li>Adding MongoDB as the database.</li>\n<li>Creating basic CRUD endpoints and testing with <a href=\"https://www.postman.com/\">Postman</a>.</li>\n<li>Uploading files and view them using MongoDB <a href=\"https://docs.mongodb.com/manual/core/gridfs\">GridFS</a>.</li>\n<li>Creating custom middleware with Express.</li>\n<li>Add logging for the web application.</li>\n<li>Securing endpoints with <a href=\"https://jwt.io/\">JWT</a> authentication.</li>\n<li>Validating the input using <a href=\"https://hapi.dev/module/joi/\">@Hapi/Joi</a>.</li>\n<li>Adding an <a href=\"https://swagger.io/specification/\">OpenAPI Swagger</a> Documentation.</li>\n<li>Caching the responses with <a href=\"https://redis.io/\">Redis</a>.</li>\n<li>Load balancing with <a href=\"https://pm2.keymetrics.io/\">PM2</a>.</li>\n<li>Testing the API using <a href=\"https://www.chaijs.com/\">Chai</a>, <a href=\"https://mochajs.org/\">Mocha</a>.</li>\n<li>Create a CI/CD pipeline.</li>\n<li>Deploying to your favorite platform.</li>\n</ol>\n<p>Well if you have done all of these things with your web application, it would be awesome. Since I learned all of these the hard way, I want to share them with all of you. Because sharing is caring 😇.</p>\n<p>Since this tutorial is a series I won’t be making this a long; boring to read one. In this first article, I will describe how to set up a simple NodeJS and Express app with SSL/TLS. Just that, nothing else.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/6LsNJMcGwfz5MxaiPSf55W/6515ce3dea77d2caceb7c434e51e4287/maxresdefault.jpg\" alt=\"maxresdefault\"></p>\n<p><strong>On your feet soldier, we are starting.</strong></p>\n<p>First of all, let’s create the folder structure of our web application.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/X8HViCF0BVbb4gPN1ojt4/909fea9e6991bbde125497f3c92d8016/1_jnP_vv30BKCx84yOSHbTRQ.png\" alt=\"1 jnP vv30BKCx84yOSHbTRQ\"></p>\n<figcaption>Figure 1: node-is-simple folder structure</figcaption>\n<p>As shown in figure 1, you need to create the folders and the <em>index.js</em> file. If you use Linux or, Git Bash on Windows, let’s make a simple script to do this. So you won’t have to do this again when you need to create another application. (We are so lazy aren’t we? 😂)</p>\n<pre><code>#!/usr/bin/env bash\n\n############################################################\n# Remember to create a folder for your project first       #\n# And run `npm init` to initialize a node project          #\n# Inside that project folder run this bootstrap.sh script  #\n############################################################\n\n# Create the folders\nmkdir config controllers errors middleware models services swagger utilities database\n\n# Create the index.js file\ntouch index.js\n\n############################################################\n# Remember to check if you have node and npm installed     #\n# I assume you have installed node and npm                 #\n############################################################\n\n# Install required packages\nnpm install express chalk --save\n\n#That's it folks!\n</code></pre>\n<p>Let’s go through it again.</p>\n<p>First, you need to create a folder for your project and run <em>npm init</em> and initialize your application. With this, you can specify a great name to your project, your license of preference, and many more. Ah, I just forgot. You need to check if you have the current version of Node and <a href=\"https://www.npmjs.com/\">NPM</a> installed in your machine. I hope you know how to install NodeJS on your computer. If not please refer to the following links.</p>\n<p><a href=\"https://www.guru99.com/download-install-node-js.html\">How to Download &#x26; Install Node.js - NPM on Windows</a></p>\n<p><a href=\"https://www.digitalocean.com/community/tutorials/how-to-install-node-js-on-ubuntu-18-04\">How To Install Node.js on Ubuntu 18.04</a></p>\n<p>After doing that just run this <em>bootstrap.sh</em> bash script inside your project folder and it will create a simple Node, Express application. So simple right?</p>\n<p>After creating the necessary folder structure let’s set up the Express application. Let’s go to the <em>index.js</em> file on the root folder and add these lines.</p>\n<pre><code>const express = require(\"express\");\nconst chalk = require(\"chalk\");\nconst http = require(\"http\");\nconst https = require(\"https\");\nconst config = require(\"./config\");\n\nconst HTTP_PORT = config.HTTP_PORT;\nconst HTTPS_PORT = config.HTTPS_PORT;\nconst SERVER_CERT = config.SERVER_CERT;\nconst SERVER_KEY = config.SERVER_KEY;\n\nconst app = express();\nconst MainController = require(\"./controllers\");\n\napp.use(\"\", MainController);\napp.set(\"port\", HTTPS_PORT);\n\n/**\n * Create HTTPS Server\n */\n\nconst server = https.createServer(\n  {\n    key: SERVER_KEY,\n    cert: SERVER_CERT\n  },\n  app\n);\n\nconst onError = error => {\n  if (error.syscall !== \"listen\") {\n    throw error;\n  }\n\n  const bind =\n    typeof HTTPS_PORT === \"string\"\n      ? \"Pipe \" + HTTPS_PORT\n      : \"Port \" + HTTPS_PORT;\n\n  switch (error.code) {\n    case \"EACCES\":\n      console.error(chalk.red(`[-] ${bind} requires elevated privileges`));\n      process.exit(1);\n      break;\n    case \"EADDRINUSE\":\n      console.error(chalk.red(`[-] ${bind} is already in use`));\n      process.exit(1);\n      break;\n    default:\n      throw error;\n  }\n};\n\nconst onListening = () => {\n  const addr = server.address();\n  const bind = typeof addr === \"string\" ? `pipe ${addr}` : `port ${addr.port}`;\n  console.log(chalk.yellow(`[!] Listening on HTTPS ${bind}`));\n};\n\nserver.listen(HTTPS_PORT);\nserver.on(\"error\", onError);\nserver.on(\"listening\", onListening);\n\n/**\n * Create HTTP Server (HTTP requests will be 301 redirected to HTTPS)\n */\nhttp\n  .createServer((req, res) => {\n    res.writeHead(301, {\n      Location:\n        \"https://\" +\n        req.headers[\"host\"].replace(\n          HTTP_PORT.toString(),\n          HTTPS_PORT.toString()\n        ) +\n        req.url\n    });\n    res.end();\n  })\n  .listen(HTTP_PORT)\n  .on(\"error\", onError)\n  .on(\"listening\", () =>\n    console.log(chalk.yellow(`[!] Listening on HTTP port ${HTTP_PORT}`))\n  );\n\nmodule.exports = app;\n</code></pre>\n<p>Don’t run this yet, since we haven’t done anything yet. I know this is a bit too much just bear with me, I’ll explain everything. What we are doing here is, first we create an HTTP server and then we create an HTTPS server. Then we redirect all the HTTP traffic to the HTTPS server. First of all, we need to create certificates to use inside the HTTPS server. It is a little bit of pain, but it’ll worth it. This is a good resource about creating SSL certificates for your Node application.</p>\n<p><a href=\"https://www.sitepoint.com/how-to-use-ssltls-with-node-js/\">How to Use SSL/TLS with Node.js</a></p>\n<p>I am a little bit of a lazy person so I’ll just generate <em>server.cert</em> and <em>server.key</em> files using this link.</p>\n<p><a href=\"https://www.selfsignedcertificate.com/\">Self-Signed Certificate Generator</a></p>\n<p>Inside the server name input, you just have to provide your domain name. For this purpose, I’ll use the <em>localhost</em> as the domain name.</p>\n<p>After generating the <em>*.cert</em> and <em>*.key</em> files copy them to the <em>/config</em> folder. And rename them to <em>server.cert</em> and <em>server.key.</em></p>\n<p>Now let’s import the certificates and make them useful. Inside the <em>/config</em> folder create the file <em>index.js</em> and add these lines.</p>\n<pre><code>const fs = require(\"fs\");\n\nconst SERVER_CERT = fs.readFileSync(__dirname + \"/server.cert\", \"utf8\");\nconst SERVER_KEY = fs.readFileSync(__dirname + \"/server.key\", \"utf8\");\n\nmodule.exports = {\n  SERVER_CERT,\n  SERVER_KEY,\n  HTTP_PORT: 8080,\n  HTTPS_PORT: 8081\n};\n</code></pre>\n<p>Not so simple after all right? Well, let’s see.</p>\n<p>Now that we have set up the certificates, let’s create a simple controller (endpoint) to our application and check that out. First, let’s got to the <em>/controllers</em> folder and create an <em>index.js</em> file. Inside that add the following lines.</p>\n<pre><code>const router = require(\"express\").Router();\nconst asyncWrapper = require(\"../utilities/async-wrapper\");\n\n/** @route  GET /\n *  @desc   Root endpoint\n *  @access Public\n */\nrouter.get(\n  \"/\",\n  asyncWrapper(async (req, res) => {\n    res.send({\n      message: \"Hello World!\",\n      status: 200\n    });\n  })\n);\n\nmodule.exports = router;\n</code></pre>\n<p><strong><em>asyncWrapper</em> what is that???</strong></p>\n<p>Let me tell you about that. Async Wrapper is a wrapper function that will catch all the errors happen inside your code and returns them to the error handling middleware. I’ll explain this a little more when I am discussing Express middleware. Now let’s create this infamous <em>asyncWrapper.</em> Go to the <em>/utilities</em> folder and create the two following files.</p>\n<p><code>**async-wrapper.js**</code></p>\n<pre><code>module.exports = requestHandler => (req, res, next) =>\n  requestHandler(req, res).catch(next);\n</code></pre>\n<p><code>**async.wrapper.d.ts**</code> (Async wrapper type definition file)</p>\n<p>We have done it, folks, we have done it. Now let’s check this beautiful Express app at work. Let’s run the web application first. Let’s go to the project folder and in the terminal (or Git Bash on Windows) run the following line.</p>\n<p><em>node index.js</em></p>\n<p>After that let’s fire up your favorite browser (mine is Chrome 😁) and hit the endpoint at,</p>\n<p><a href=\"https://localhost:8081/\">https://localhost:8081/</a></p>\n<p>Don’t worry if your browser says it is not secure to go to this URL. You trust yourself, don’t you? So let’s accept the risk and go ahead.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/6376WfRDmfD2l7nNerhgOE/e67006295d61ab844c1e8531827330de/1_-j7gNIpPkuqIQj_OQf9Y0A.png\" alt=\"1 -j7gNIpPkuqIQj OQf9Y0A\"></p>\n<figcaption>This is the warning I told you about. (FYI, this screenshot is from Firefox)</figcaption>\n<p>Now if you can see something like this,</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/5fBDIxDCiysuWEzT5A05vb/de95f050a10cc91ab51695f37ea1506c/1_UNQTECXa-hXe2YM4ANG0DQ.png\" alt=\"1 UNQTECXa-hXe2YM4ANG0DQ\"></p>\n<figcaption>Response from [https://localhost:8081](https://localhost:8081)</figcaption>\n<p>You have successfully created a NodeJS, Express application. Also since we have set up an HTTP server, you can try this URL too. <a href=\"http://localhost:8080/\">http://localhost:8080</a></p>\n<p>If you go to this URL, you’ll see that you’ll be redirected to <a href=\"https://localhost:8081/\">https://localhost:8081</a></p>\n<p>Now that’s the magic with our Express application. Awesome right? So this is it for this tutorial. In the next tutorial, I’ll tell you all about adding MongoDB as the database.</p>\n<p><a href=\"https://github.com/Niweera/node-is-simple\">https://github.com/Niweera/node-is-simple</a></p>\n<p>This is the GitHub repo for this tutorial and I’ll update this repo as the tutorial grows. Check for the commit messages for the snapshot of the repo for a particular tutorial. If you have any queries, don’t forget to hit me up on any social media as shown on my website.</p>\n<p><a href=\"https://niweera.gq\">https://niweera.gq/</a></p>\n<p>So until we meet again with part two of this tutorial series, happy coding…</p>"}},"categories":[{"name":"Node.js","slug":"node-js"},{"name":"How To","slug":"how-to"}]}},{"node":{"slug":"running-your-node-js-app-with-systemd-part-1","title":"Running Your Node.js App With Systemd - Part 1","image":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/7hMby0z6l7JP5c9uQWoz0T/b543178d4eff1f68fd23dad178eeee44/5-min.jpg","fileName":"5-min.jpg"}},"bodyContent":{"childMarkdownRemark":{"html":"<p>You've written the next great application, in Node, and you are ready to unleash it upon the world. Which means you can no longer run it on your laptop, you're going to actually have to put it up on some server somewhere and connect it to the real Internet. Eek.</p>\n<p>There are a lot of different ways to run an app in production. This post is going to cover the specific case of running something on a \"standard\" Linux server that uses <code>systemd</code>, which means that we are <strong>not</strong> going to be talking about using Docker, AWS Lambda, Heroku, or any other sort of managed environment. It's just going to be you, your code, and terminal with a <code>ssh</code> session my friend.</p>\n<p>Before we get started though, let's talk for just a brief minute about what <code>systemd</code> actually is and why you should care.</p>\n<h2>What is <code>systemd</code> Anyway?</h2>\n<p>The full answer to this question is big, as in, \"ginormous\" sized big. So we're not going to try and answer it fully since we want to get on the the part where we can launch our app. What you need to know is that <code>systemd</code> is a thing that runs on \"new-ish\" Linux servers that is responsible for starting / stopping / restarting programs for you. If you install <code>mysql</code>, for example, and whenever you reboot the server you find that <code>mysql</code> is already running for you, that happens because <code>systemd</code> knows to turn <code>mysql</code> on when the machine boots up.</p>\n<p>This <code>systemd</code> machinery has replaced older systems such as <code>init</code> and <code>upstart</code> on \"new-ish\" Linux systems. There is a lot of arguably justified angst in the world about exactly how <code>systemd</code> works and how intrusive it is to your system. We're not here to discuss that though. If your system is \"new-ish\", it's using <code>systemd</code>, and that's what we're all going to be working with for the forseeable future.</p>\n<p>What does \"new-ish\" mean specifically? If you are using any of the following, you are using <code>systemd</code>:</p>\n<ul>\n<li>CentOS 7 / RHEL 7</li>\n<li>Fedora 15 or newer</li>\n<li>Debian Jessie or newer</li>\n<li>Ubuntu Xenial or newer</li>\n</ul>\n<h2>Running our App Manually</h2>\n<p>I'm going to assume you have a fresh installation of <a href=\"http://releases.ubuntu.com/16.04/\">Ubuntu Xenial</a> to work with, and that you have set up a default user named <code>ubuntu</code> that has <code>sudo</code> privileges. This is what the default will be if you spin up a Xenial instance in Amazon EC2. I'm using Xenial because it is currently the newest LTS (Long Term Support) version available from Canonical. Ubuntu Yakkety is available now, and is even <em>newer</em>, but Xenial is quite up-to-date at the time of this writing and will be getting security updates for many years to come because of its LTS status.</p>\n<p>Use <code>ssh</code> with the <code>ubuntu</code> user to get into your server, and let's install Node.</p>\n<pre><code>$ sudo apt-get -y install curl\n$ curl -sL https://deb.nodesource.com/setup_6.x | sudo bash -\n$ sudo apt-get -y install nodejs\n</code></pre>\n<p>Next let's create an app and run it manually. Here's a trivial app I've written that simply echoes out the user's environment variables.</p>\n<pre><code class=\"language-javascript\">const http = require('http');\n\nconst hostname = '0.0.0.0';\nconst port = process.env.NODE_PORT || 3000;\nconst env = process.env;\n\nconst server = http.createServer((req, res) => {\n  res.statusCode = 200;\n  res.setHeader('Content-Type', 'text/plain');\n  for (var k in env) {\n    res.write(k + \": \" + env[k] + \"\\n\");\n  }\n  res.end();\n});\n\nserver.listen(port, hostname, () => {\n  console.log(\"Server running at http://\" + hostname + \":\" + port + \"/\");\n});\n</code></pre>\n<p>Using your text editor of choice (which should obviously be <a href=\"https://www.gnu.org/software/emacs/\">Emacs</a> but I suppose it's a free country if you want to use something inferior), create a file called <code>hello_env.js</code> in the user's home directory <code>/home/ubuntu</code> with the contents above. Next run it with</p>\n<pre><code>$ /usr/bin/node /home/ubuntu/hello_env.js\n</code></pre>\n<p>You should be able to go to</p>\n<pre><code>http://11.22.33.44:3000\n</code></pre>\n<p>in a web browser now, substituting <code>11.22.33.44</code> with whatever the actual IP address of your server is, and see a printout of the environment variables for the <code>ubuntu</code> user. If that is in fact what you see, great! We know the app runs, and we know the command needed to start it up. Go ahead and press <code>Ctrl-c</code> to close down the application. Now we'll move on to the <code>systemd</code> parts.</p>\n<h2>Creating a <code>systemd</code> Service File</h2>\n<p>The \"magic\" that's needed to make <code>systemd</code> start working for us is a text file called a <code>service</code> file. I say \"magic\" because for whatever reason, this seems to be the part that people block on when they are going through this process. Fortunately, it's much less difficult and scary than you might think.</p>\n<p>We will be creating a file in a \"system area\" where everything is owned by the root user, so we'll be executing a bunch of commands using <code>sudo</code>. Again, don't be nervous, it's really very straightforward.</p>\n<p>The service files for the things that <code>systemd</code> controls all live under the directory path</p>\n<pre><code>/lib/systemd/system\n</code></pre>\n<p>so we'll create a new file there. If you're using <a href=\"https://www.nano-editor.org/\">Nano</a> as your editor, open up a new file there with:</p>\n<pre><code>sudo nano /lib/systemd/system/hello_env.service\n</code></pre>\n<p>and put the following contents in it:</p>\n<pre><code>[Unit]\nDescription=hello_env.js - making your environment variables rad\nDocumentation=https://example.com\nAfter=network.target\n\n[Service]\nEnvironment=NODE_PORT=3001\nType=simple\nUser=ubuntu\nExecStart=/usr/bin/node /home/ubuntu/hello_env.js\nRestart=on-failure\n\n[Install]\nWantedBy=multi-user.target\n</code></pre>\n<p>Let's go ahead and talk about what's in that file. In the <code>[Unit]</code> section, the <code>Description</code> and <code>Documentation</code> variables are obvious. What's less obvious is the part that says</p>\n<pre><code>After=network.target\n</code></pre>\n<p>That tells <code>systemd</code> that if it's supposed to start our app when the machine boots up, it should wait until after the main networking functionality of the server is online to do so. This is what we want, since our app can't bind to <code>NODE_PORT</code> until the network is up and running.</p>\n<p>Moving on to the <code>[Service]</code> section we find the meat of today's project. We can specify environment variables here, so I've gone ahead and put in:</p>\n<pre><code>Environment=NODE_PORT=3001\n</code></pre>\n<p>so our app, when it starts, will be listening on port 3001. This is different than the default 3000 that we saw when we launched the app by hand. You can specify the <code>Environment</code> directive multiple times if you need multiple environment variables. Next is</p>\n<pre><code>Type=simple\n</code></pre>\n<p>which tells <code>systemd</code> how our app launches itself. Specifically, it lets <code>systemd</code> know that the app won't try and fork itself to drop user privileges or anything like that. It's just going to start up and run. After that we see</p>\n<pre><code>User=ubuntu\n</code></pre>\n<p>which tells <code>systemd</code> that our app should be run as the unprivileged <code>ubuntu</code> user. You definitely want to run your apps as unprivileged users to that attackers can't aim at something running as the <code>root</code> user.</p>\n<p>The last two parts here are maybe the most interesting to us</p>\n<pre><code>ExecStart=/usr/bin/node /home/ubuntu/hello_env.js\nRestart=on-failure\n</code></pre>\n<p>First, <code>ExecStart</code> tells <code>systemd</code> what command it should run to launch our app. Then, <code>Restart</code> tells <code>systemd</code> under what conditions it should restart the app if it sees that it has died. The <code>on-failure</code> value is likely what you will want. Using this, the app will <em>NOT</em> restart if it goes away \"cleanly\". Going away \"cleanly\" means that it either exits by itself with an exit value of <code>0</code>, or it gets killed with a \"clean\" signal, such as the default signal sent by the <code>kill</code> command. Basically, if our app goes away because we want it to, then <code>systemd</code> will leave it turned off. However, if it goes away for any other reason (an unhandled exception crashes the app, for example), then <code>systemd</code> will immediately restart it for us. If you want it to restart no matter what, change the value from <code>on-failure</code> to <code>always</code>.</p>\n<p>Last is the <code>[Install]</code> stanza. We're going to gloss over this part as it's not very interesting. It tells <code>systemd</code> how to handle things if we want to start our app on boot, and you will probably want to use the values shown for most things until you are a more advanced <code>systemd</code> user.</p>\n<h2>Using <code>systemctl</code> To Control Our App</h2>\n<p>The hard part is done! We will now learn how to use the system provided tools to control our app. To being with, enter the command</p>\n<pre><code>$ sudo systemctl daemon-reload\n</code></pre>\n<p>You have to do this whenever <strong>any</strong> of the service files change <strong>at all</strong> so that <code>systemd</code> picks up the new info.</p>\n<p>Next, let's launch our app with</p>\n<pre><code>$ sudo systemctl start hello_env\n</code></pre>\n<p>After you do this, you should be able to go to</p>\n<pre><code>http://11.22.33.44:3001\n</code></pre>\n<p>in your web browser and see the output. If it's there, congratulations, you've launched your app using <code>systemd</code>! If the output looks very different than it did when you launched the app manually don't worry, that's normal. When <code>systemd</code> kicks off an application, it does so from a <em>much more minimal environment</em> than the one you have when you <code>ssh</code> into a machine. In particular, the <code>$HOME</code> environment variable may not be set by default, so be sure to pay attention to this if your app makes use of any environment variables. You may need to set them yourself when using <code>systemd</code>.</p>\n<p>You may be interested in what state <code>systemd</code> thinks the app is in, and if so, you can find out with</p>\n<pre><code>$ sudo systemctl status hello_env\n</code></pre>\n<p>Now, if you want to stop your app, the command is simply</p>\n<pre><code>$ sudo systemctl stop hello_env\n</code></pre>\n<p>and unsurprisingly, the following will restart things for us</p>\n<pre><code>$ sudo systemctl restart hello_env\n</code></pre>\n<p>If you want to make the application start up when the machine boots, you accomplish that by <em>enabling</em> it</p>\n<pre><code>$ sudo systemtl enable hello_env\n</code></pre>\n<p>and finally, if you previously enabled the app, but you change your mind and want to stop it from coming up when the machine starts, you correspondingly <em>disable</em> it</p>\n<pre><code>$ sudo systemctl disable hello_env\n</code></pre>\n<h2>Wrapping Up</h2>\n<p>That concludes today's exercise. There is much, much more to learn and know about <code>systemd</code>, but this should help get you started with some basics. In a follow up blog post, we will learn how to launch multiple instances of our app, and load balance those behind <a href=\"https://nginx.org\">Nginx</a> to illustrate a more production ready example.</p>\n<hr>\n<p>This article was first published <a href=\"https://nodesource.com/blog/running-your-node-js-app-with-systemd-part-1/\">NodeSource blog post</a> in November 2016</p>"}},"categories":[{"name":"How To","slug":"how-to"},{"name":"Node.js","slug":"node-js"}]}},{"node":{"slug":"configuring-your-npmrc-for-an-optimal-node-js-environment","title":"Configuring Your .npmrc for an Optimal Node.js Environment","image":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/1DTT5AD0XSonP7LBHxXJdR/d9c15a40f2752a3517f38098476c1398/6-min.jpg","fileName":"6-min.jpg"}},"bodyContent":{"childMarkdownRemark":{"html":"<p>This blog post was first published on March 2017. Find out more <a href=\"https://nodesource.com/blog/configuring-your-npmrc-for-an-optimal-node-js-environment\">here</a></p>\n<hr>\n<p>For Node.js developers, <code>npm</code> is an everyday tool. It's literally something we interact with multiple times on a daily basis, and it's one of the pieces of the ecosystem that's led to the success of Node.js. </p>\n<p>One of the most useful, important, and enabling aspects of the <code>npm</code> CLI is that its <em>highly</em> configurable. It provides an enormous amount of configurability that enables everyone from huge enterprises to individual developers to use it effectively. </p>\n<p>One part of this high-configurability is the <code>.npmrc</code> file. For a long time I'd seen discussion about it - the most memorable being the time I thought you could change the name of the <code>node_modules</code> directory with it. For a long time, I didn't truly understand just how useful the <code>.npmrc</code> file could be, or how to even <em>use</em> it. </p>\n<p>So, today I've collected a few of the optimizations that <code>.npmrc</code> allows that have been awesome for speeding up my personal workflow when scaffolding out Node.js modules and working on applications long-term. </p>\n<h2>Automating <code>npm init</code> Just a <em>Bit</em> More</h2>\n<p>When you're creating a new module from scratch, you'll <em>typically</em> start out with the <code>npm init</code> command. One thing that some developers don't know is that you can actually automate this process fairly heftily with a few choice <code>npm config set ...</code> commands that set default values for the <code>npm init</code> prompts.</p>\n<p>You can easily set your name, email, URL, license, and initial module version with a few commands:</p>\n<pre><code class=\"language-bash\">npm config set init.author.name \"Hiro Protagonist\"\nnpm config set init.author.email \"hiro@showcrash.io\"\nnpm config set init.author.url \"http://hiro.snowcrash.io\"\nnpm config set init.license \"MIT\"\nnpm config set init.version \"0.0.1\"\n</code></pre>\n<p>In the above example, I've set up some defaults for Hiro. This personal information won't change too frequently, so setting up some defaults is helpful and allows you to skip over entering the same information in manually every time. </p>\n<p>Additionally, the above commands set up two defaults that are related to your module. </p>\n<p>The first default is the initial license that will be automatically suggested by the <code>npm init</code> command. I personally like to default to <code>MIT</code>, and much of the rest of the Node.js ecosystem does the same. That said, you can set this to whatever you'd like - it's a nice optimization to just be able to nearly automatically select your license of choice.</p>\n<p>The second default is the initial version. This is actually one that made me happy, as whenever I tried building out a module I never wanted it to start out at version <code>1.0.0</code>, which is what <code>npm init</code> defaults to. I personally set it to <code>0.0.1</code> and then increment the version as I go with the <code>npm version [ major | minor | patch ]</code> command.</p>\n<h2>Change Your npm Registry</h2>\n<p>As time moves forward, we're seeing more options for registries arise. For example, you may want to set your registry to a cache of the modules you know you need for your apps. Or, you may be using <a href=\"https://nodesource.com/products/certified-modules\">Certified Modules</a> as a custom npm registry. There's even a separate registry for Yarn, a topic that is both awesome and totally out of scope for this post.</p>\n<p>So, if you'd like to set a custom registry, you can run a pretty simple one-line command:</p>\n<pre><code class=\"language-bash\">npm config set registry \"https://my-custom-registry.registry.nodesource.io/\"\n</code></pre>\n<p>In this example, I've set the registry URL to an example of a Certified Modules registry - that said, the exact URL in the command can be replaced with <em>any</em> registry that's compatible. To reset your registry back to the default npm registry, you can simply run the same command pointing to the standard registry:</p>\n<pre><code class=\"language-bash\">npm config set registry \"https://registry.npmjs.com/\"\n</code></pre>\n<h2>Changing the console output of <code>npm install</code> with loglevel</h2>\n<p>When you <code>npm install</code> a <em>bunch</em> of information gets piped to you. By default, the <code>npm</code> command line tool limits how much of this information is actually output into the console when installing. There are varying degrees of output that you can assign at install, or by default, if you change it with <code>npm config</code> in your <code>.npmrc</code> file. The options, from least to most output, are: <code>silent</code>, <code>error</code>, <code>warn</code>, <code>http</code>, <code>info</code>, <code>verbose</code>, and <code>silly</code>.</p>\n<p>Here's an example of the <code>silent</code> loglevel:\n<img src=\"//images.contentful.com/hspc7zpa5cvq/4W74xwLugw6EoOSISIUwie/0d9f29dd32c4e39de5b98ba46d138a19/npm_install_express_loglevel_silent.gif\" alt=\"npm install express loglevel silent\"></p>\n<p>And here's an example of the <code>silly</code> loglevel:\n<img src=\"//images.contentful.com/hspc7zpa5cvq/6p7v2EFSTuSw860Y0EUgeU/449080a2f1bd32910ce2e23358381bca/npm_install_express_loglevel_silly.gif\" alt=\"npm install express loglevel silly\"></p>\n<p>If you'd like to get a bit more information (or a bit less, depending on your preferences) when you <code>npm install</code>, you can change the default loglevel.</p>\n<pre><code class=\"language-bash\">npm config set loglevel=\"http\"\n</code></pre>\n<p>If you tinker around with this config a bit and would like to reset to what the <code>npm</code> CLI <em>currently</em> defaults to, you can run the above command with <code>warn</code> as the loglevel:</p>\n<pre><code class=\"language-bash\">npm config set loglevel=\"warn\"\n</code></pre>\n<div class=\"blog-cta nsolid\" style=\"background-color: #4cb5ff;\">\n\tLooking for more info on npm? Check out our complete guide: \n  <a class=\"button more large\" href=\"https://pages.nodesource.com/npm-guide-ultimate-wb.html?utm_campaign=blogref&utm_source=blog&utm_content=blog-confignpmrc\">Read now: The Ultimate Guide to npm</a>\n</div>\n<h2>Change Where npm Installs Global Modules</h2>\n<p>This is a really awesome change - it has a few steps, but is really worth it. With a few commands, you can change where the <code>npm</code> CLI installs global modules by default. Normally, it installs them to a privileged system folder - this requires administrative access, meaning that a global install requires <code>sudo</code> access on UNIX-based systems.</p>\n<p>If you change the default global prefix for <code>npm</code> to an unprivileged directory, for example, <code>~/.global-modules</code>, you'll not need to authenticate when you install a global module. That's one benefit - another is that globally installed modules won't be in a system directory, reducing the likelihood of a malicious module (intentionally or not) doing something you didn't want it to on your system.</p>\n<p>To get started, we're going to create a new folder called <code>global-modules</code> and set the npm prefix to it:</p>\n<pre><code class=\"language-bash\">mkdir ~/.global-modules\nnpm config set prefix \"~/.global-modules\"\n</code></pre>\n<p>Next, if you don't already have a file called <code>~/.profile</code>, create one in your root user directory. Now, add the following line to the <code>~/.profile</code> file:</p>\n<pre><code class=\"language-bash\">export PATH=~/.global-modules/bin:$PATH\n</code></pre>\n<p>Adding that line to the <code>~/.profile</code> file will add the <code>global-modules</code> directory to your PATH, and enable you to use it for npm global modules. </p>\n<p>Now, flip back over to your terminal and run the following command to update the PATH with the newly updated file:</p>\n<pre><code class=\"language-bash\">source ~/.profile\n</code></pre>\n<h2>Just one more thing...</h2>\n<p>If you'd like to keep reading about Node.js, npm, configuration options, and development with the Node.js stack, I've got some <strong>fantastic</strong> articles for you. </p>\n<p>Our most recent guide is a deep-dive into <a href=\"https://nodesource.com/blog/the-basics-of-package-json-in-node-js-and-npm\">the core concepts of the package.json file</a>. You'll find a <strong>ton</strong> of info about <code>package.json</code> in there, including a ton of super helpful configuration information. We also published an <a href=\"https://nodesource.com/blog/an-absolute-beginners-guide-to-using-npm\">absolute beginner's guide to npm</a> that you may be interested in reading - even though it's a beginner's guide, I'd bet you'll find <em>something</em> useful in it.</p>\n<p>With this article, the intent was to help you set up a great configuration for Node.js development. If you'd like to take the leap and ensure that you're always on a rock-solid platform when developing and deploying you Node.js apps, check out NodeSource Certified Modules - it's a new tool we launched last week that will help enable you to spend more time building apps and less time worrying about modules.</p>\n<div class=\"blog-cta certified-modules\">\n\tLearn more and get started with NCM \n  <a class=\"button more large\" href=\"https://accounts.nodesource.com/sign-up-blogref/?utm_campaign=blogref&utm_source=blog&utm_content=blog-confignpmrc\">Create your free NodeSource account</a>\n</div>"}},"categories":[{"name":"How To","slug":"how-to"},{"name":"Node.js","slug":"node-js"}]}}]},"contentfulHero":{"headLine":"Your latest Node.js content, news and updates in one place.","coverImage":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/1ZgP9Kv0C8g1nuEX3zTs2a/f00ee931ce94307ccf8a62c17d3d67d2/social-bg-12__1_-min.png","fileName":"social-bg-12 (1)-min.png"}}}},"pageContext":{"categoryId":"50768c9e-fc69-55ce-8a68-88617e5bcfbd","category":"How To","limit":7,"skip":0,"numPages":2,"currentPage":1,"prevPath":"","nextPath":"/category/how-to/page/2"}}}