{"componentChunkName":"component---src-templates-posts-js","path":"/blogs/page/2","result":{"data":{"allContentfulPost":{"edges":[{"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":"new-node-js-14-features-will-see-it-disrupt-ai-iot-and-more-node-latest","title":"New Node.js 14 features will see it disrupt AI, IoT and more, Node latest version report","image":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/5xhMzxcERft4xDTeCMugR0/dabf4e6950a3143996589c55c1437b0d/nodejs-14-features___1_.jpg","fileName":"nodejs-14-features_ (1).jpg"}},"bodyContent":{"childMarkdownRemark":{"html":"<p><strong>New or latest Node.js features aren’t the usual selling point of this platform. Node.js is primarily well-known for its speed and simplicity. This is why so many companies are willing to give it a shot. However, with the release of a new LTS (long-term support) Node.js 14 version, Node.js will gain a lot of new features every Node.js developer can be excited about. Why? That’s because the new Node.js features added in the version 12 through 14 and the possibilities they create are simply that amazing! Find our more from this Node latest version report.</strong></p>\n<p>This article has been updated to reflect the latest changes added in Node.js 14. What you can find here is a thorough overview of the latest Node.js features added in version 12 through 14.</p>\n<h2>Node + Web Assembly = &#x3C;3</h2>\n<p>Web Assembly is slowly gaining in popularity. More and more Node modules are experimenting with this language and so is Node itself! With the upcoming Node 14 release, we will gain access to the experimental Web Assembly System Interface – WASI.</p>\n<p>The main idea behind this is to provide us with an easier way to access the underlying operating system. I’m really looking forward to seeing more Web Assembly in Node.</p>\n<h2>V8 8.1 is here!</h2>\n<p>I did mention that the new Node comes with the V8. This gives us not only access to the private field, but also some performance optimizations.</p>\n<p>Awaits should work much faster, as should JS parsing.</p>\n<p>Our apps should load quicker and asyncs should be much easier to debug, because we’re finally getting stack traces for them.</p>\n<p>What’s more, the heap size is getting changed. Until now, it was either 700MB (for 32bit systems) or 1400MB (for 64bit). With new changes, it’s based on the available memory!</p>\n<p>With the latest Node version 14, we’re getting access to the newest V8. This means that we’re getting some popular features of the JavaScript engine.</p>\n<p>If you’re using TypeScript, you probably try nullish coalescing and optional chaining. Both of those are natively supported by Node 14.</p>\n<p>We’re also getting a few updates to Intl. The first one is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames\">support for Intl.DisplayNames</a> and the second one is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat\">support for calendar and numberingSystem for Intl.DateTimeFormat</a>.</p>\n<h2>Stable Diagnostic Reports</h2>\n<p>In Node 12, we’ve got a new experimental feature called Diagnostic Reports. By using it, we could easily get a report that contains information about the current system. What’s more, we can generate it not only on demand but also after a certain event.</p>\n<p>If you have any production running a Node app, then this is something you should be checking out.</p>\n<h2>Threads are almost stable!</h2>\n<p>With the last LTS we’ve got access to threads. Of course, it was an experimental feature and required a special flag called –experimental-worker for it to work.</p>\n<p>With the upcoming LTS (Node 12) it’s still experimental, but won’t require a flag anymore. We are getting closer to a stable version!</p>\n<h2>ES modules support</h2>\n<p>Let’s face it, ES modules are currently the way to go in JavaScript development. We are using it in our frontend apps. We are using it on our desktop or even mobile apps. And yet, in case of Node we were stuck with common.js modules.</p>\n<p>Of course, we could use Babel or Typescript, but since Node.js is a backend technology, the only thing we should care about is a Node version installed on the server. We don’t need to care about multiple different browsers and support for them, so what’s the point of installing a tool that was made precisely with that in mind (Babel/Webpack etc.)?</p>\n<p>With Node 10, we could finally play a little with ES modules (current LTS has experimental implementation for modules), but it required us to use special file extension – .mjs (module javascript).</p>\n<p>With Node 12, it’s getting a little bit easier to work with. Much like it is with web apps, we get a special property type called that will define if code should be treated like common.js or es module.</p>\n<p>The only thing you need to do to treat all your files as a module is to add the property type with the value module to your package.json.</p>\n<pre><code>{\n  \"type\": \"module\"\n}\n</code></pre>\n<p>From now on, if this package.json is the closest to our .js file, it will be treated like a module. No more mjs (we can still use it if we want to)!</p>\n<p>So, what if we wanted to use some common.js code?</p>\n<p>As long as the closest package.json does not contain a module type property, it will be treated like common.js code.</p>\n<p>What’s more, we are getting new an extension called <strong>cjs</strong> – a common.js file.</p>\n<p>Every mjs file is treated as a module and every <strong>cjs</strong> as a common.js file.</p>\n<p>If you didn’t have a chance to try it out, now is the time!</p>\n<blockquote>\n<p>Interested in developing microservices? 🤔 Make sure to check out our <a href=\"https://tsh.io/state-of-microservices/\">State of Microservices 2020 report</a> – based on opinions of 650+ microservice experts!</p>\n</blockquote>\n<h2>JS and private variables</h2>\n<p>When it comes to JavaScript, we have always struggled to protect some data in our classes/functions from the outside.</p>\n<p>JS is famous for its monkey patching, meaning we could always somehow access almost everything.</p>\n<p>We tried with closures, symbols and more to simulate private-like variables. Node 12 ships with the new V8 and so we’ve got access to one cool feature – private properties in the class.</p>\n<p>I’m sure you all remember the old approach to privates in Node:</p>\n<pre><code>class MyClass {\n  constructor() {\n    this._x = 10\n  }\n  \n  get x() {\n    return this._x\n  }\n}\n</code></pre>\n<p>We all know it’s not really a private – we are still able to access it anyway, but most of IDEs treated it like a private field and most of Node devs knew about this convention. Finally, we can all forget about it.</p>\n<pre><code>class MyClass {\n  #x = 10\n  \n  get x() {\n    return this.#x\n  }\n}\n</code></pre>\n<p>Can you see the difference? Yes, we use # character to tell Node that this variable is private and we want it to be accessible only from the inside of this class.</p>\n<p>Try to access it directly, you’ll get an error that this variable does not exists.</p>\n<p>Sadly some IDE do not recognize them as proper variables yet.</p>\n<h2>Flat and flatMap</h2>\n<p>With Node 12, we’re getting access to new JavaScript features.</p>\n<p>First of all, we’re getting access to new array methods – flat and flatMap. The first one is similar to Lodash’s flattenDepth method.</p>\n<p>If we pass a nested arrays to it, we will get a flatten array as a result.</p>\n<pre><code>[10, [20, 30], [40, 50, [60, 70]]].flat() // => [10, 20, 30, 40, 50, [60, 70]]\n[10, [20, 30], [40, 50, [60, 70]]].flat(2) // => [10, 20, 30, 40, 50, 60, 70]\n</code></pre>\n<p>As you can see, it also has a special parameter <strong>– depth.</strong> By using it, you can decide how many levels down you want to flatten.</p>\n<p>The second one <strong>– flatMap –</strong> works just like map, followed by flat 🙂</p>\n<h2>Optional catch binding</h2>\n<p>Another new feature is optional catch binding. Until now we always had to define an error variable for <strong>try – catch</strong>.</p>\n<pre><code>try {\n  someMethod()\n} catch(err) {\n  // err is required\n}\n</code></pre>\n<p>With Node 12 we can’t skip the entire catch clause, but we can skip the variable at least.</p>\n<pre><code>try {\n  someMethod()\n} catch {\n  // err is optional\n}\n</code></pre>\n<h2>Object.fromEntries</h2>\n<p>Another new JavaScript feature is the Object.fromEntries method. It’s main usage is to create an object either from Map or from a key/value array.</p>\n<pre><code>Object.fromEntries(new Map([['key', 'value'], ['otherKey', 'otherValue']]));\n// { key: 'value', otherKey: 'otherValue' }\n\n\nObject.fromEntries([['key', 'value'], ['otherKey', 'otherValue']]);\n// { key: 'value', otherKey: 'otherValue' }\n</code></pre>\n<h2>The new Node.js is all about threads!</h2>\n<p>If there is one thing we can all agree on, it’s that every programming language has its pros and cons. Most popular technologies have found their own niche in the world of technology. Node.js is no exception.</p>\n<p>We’ve been told for years that <a href=\"https://tsh.io/blog/serverless-in-node-js-beginners-guide/\">Node.js is good for API gateways</a> and real-time dashboards (<a href=\"https://tsh.io/blog/php-websocket/\">e.g. with websockets</a>). As a matter of fact, its design itself forced us to depend on the microservice architecture to overcome some of its common obstacles.</p>\n<p>At the end of the day, we knew that Node.js was simply not meant for time-consuming, CPU-heavy computation or blocking operations due to its single-threaded design. This is the nature of the event loop itself.</p>\n<p>If we block the loop with a complex synchronous operation, it won’t be able to do anything until it’s done. That’s the very reason we use async so heavily or move time-consuming logic to a separate microservice.</p>\n<p>This workaround may no longer be necessary thanks to new Node.js features that debuted in its 10 version. <strong>The tool that will make the difference are worker threads.</strong> Finally, Node.js will be able to excel in fields where normally we would use a different language.</p>\n<p>A good example could be AI, machine learning or big data processing. Previously, all of those required CPU-heavy computation, which left us no choice, but to build another service or pick a better-suited language. No more.</p>\n<h2>Threads!? But how?</h2>\n<p>This new Node.js feature is still experimental – it’s not meant to be used in a production environment just yet. Still, we are free to play with it. So where do we start?</p>\n<p>Starting from Node 12+ we no longer need to use special feature flag <strong>–experimental-worker</strong>. Workers are on by default!</p>\n<p><strong>node index.js</strong></p>\n<p>Now we can take full advantage of the worker_threads module. Let’s start with a simple HTTP server with two methods:</p>\n<p>→ GET /hello (returning JSON object with “Hello World” message),</p>\n<p>→ GET /compute (loading a big JSON file multiple times using a synchronous method).</p>\n<pre><code>const express = require('express');\nconst fs = require('fs');\n\nconst app = express();\n\napp.get('/hello', (req, res) => {\n  res.json({\n    message: 'Hello world!'\n  })\n});\n\napp.get('/compute', (req, res) => {\n  let json = {};\n  for (let i=0;i&#x3C;100;i++) {\n    json = JSON.parse(fs.readFileSync('./big-file.json', 'utf8'));\n  }\n\n  json.data.sort((a, b) => a.index - b.index);\n\n  res.json({\n    message: 'done'\n  })\n});\n\napp.listen(3000);\n</code></pre>\n<p>The results are easy to predict. When GET /compute and /hello are called simultaneously, we have to wait for the compute path to finish before we can get a response from our hello path. The Event loop is blocked until file loading is done.</p>\n<p>Let’s fix it with threads!</p>\n<pre><code>const express = require('express');\nconst fs = require('fs');\nconst { Worker, isMainThread, parentPort, workerData } = require('worker_threads');\n\nif (isMainThread) {\n  console.log(\"Spawn http server\");\n\n  const app = express();\n\n  app.get('/hello', (req, res) => {\n    res.json({\n      message: 'Hello world!'\n    })\n  });\n\n  app.get('/compute', (req, res) => {\n\n    const worker = new Worker(__filename, {workerData: null});\n    worker.on('message', (msg) => {\n      res.json({\n        message: 'done'\n      });\n    })\n    worker.on('error', console.error);\n      worker.on('exit', (code) => {\n        if(code != 0)\n          console.error(new Error(`Worker stopped with exit code ${code}`))\n    });\n  });\n\n  app.listen(3000);\n} else {\n  let json = {};\n  for (let i=0;i&#x3C;100;i++) {\n    json = JSON.parse(fs.readFileSync('./big-file.json', 'utf8'));\n  }\n\n  json.data.sort((a, b) => a.index - b.index);\n\n  parentPort.postMessage({});\n}\n</code></pre>\n<p>As you can see, the syntax is very similar to what we know from Node.js scaling with Cluster. But the interesting part begins here.</p>\n<p>Try to call both paths at the same time. Noticed something? Indeed, the event loop is no longer blocked so we can call /hello during file loading.</p>\n<p>Now, this is something we have all been waiting for! All that’s left is to wait for a stable API.</p>\n<h2>Want even more new Node.js features? Here is an N-API for building C/C++ modules!</h2>\n<p>The raw speed of Node.js is one of the reason we choose this technology. Worker threads are the next step to improve it. But is it really enough?</p>\n<p>Node.js is a C-based technology. Naturally, we use JavaScript as a main programming language. But what if we could use C for more complex computation?</p>\n<p>Node.js 10 gives us a stable N-API. It’s a standardized API for native modules, making it possible to build modules in C/C++ or even Rust. Sounds cool, doesn’t it?</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/7ioxRx9zuGmwxyTbCUl8mE/83c35529356d1b1bf103d5e43cb162ca/c-logo-267x300.png\" alt=\"c-logo-267x300\">\nBuilding native Node.js modules in C/C++ has just got way easier</p>\n<p>A very simple native module can look like this:</p>\n<pre><code>#include &#x3C;napi.h>\n#include &#x3C;math.h>\n\nnamespace helloworld {\n    Napi::Value Method(const Napi::CallbackInfo&#x26; info) {\n        Napi::Env env = info.Env();\n        return Napi::String::New(env, \"hello world\");\n    }\n\n    Napi::Object Init(Napi::Env env, Napi::Object exports) {\n        exports.Set(Napi::String::New(env, \"hello\"),\n                    Napi::Function::New(env, Method));\n        return exports;\n    }\n\n    NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)\n}\n</code></pre>\n<p>If you have a basic knowledge of C++, it’s not too hard to write a custom module. The only thing you need to remember is to convert C++ types to Node.js at the end of your module.</p>\n<p>Next thing we need is binding:</p>\n<pre><code>{\n    \"targets\": [\n        {\n            \"target_name\": \"helloworld\",\n            \"sources\": [ \"hello-world.cpp\"],\n            \"include_dirs\": [\"&#x3C;!@(node -p \\\"require('node-addon-api').include\\\")\"],\n            \"dependencies\": [\"&#x3C;!(node -p \\\"require('node-addon-api').gyp\\\")\"],\n            \"defines\": [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]\n        }\n    ]\n}\n</code></pre>\n<p>This simple configuration allows us to build *.cpp files, so we can later use them in Node.js apps.</p>\n<p>Before we can make use of it in our JavaScript code, we have to build it and configure our package.json to look for gypfile (binding file).</p>\n<pre><code>{\n  \"name\": \"n-api-example\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"install\": \"node-gyp rebuild\"\n  },\n  \"gypfile\": true,\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"node-addon-api\": \"^1.5.0\",\n    \"node-gyp\": \"^3.8.0\"\n  }\n}\n</code></pre>\n<p>Once the module is good to go, we can use the node-gyp rebuild command to build and then require it in our code. Just like any popular module we use!</p>\n<pre><code>const addon = require('./build/Release/helloworld.node');\n\nconsole.log(addon.hello());\n</code></pre>\n<p>Together with worker threads, N-API gives us a pretty good set of tools to build high-performance apps. Forget APIs or dashboards – even complex data processing or machine learning systems are far from impossible. Awesome!</p>\n<h2>Full support for HTTP/2 in Node.js? Sure, why not!</h2>\n<p>We’re able to <strong>compute faster</strong>. We’re able to compute in parallel. So how about assets and pages serving?</p>\n<p>For years, we were stuck with the good old http module and HTTP/1.1. As more and more assets are being served by our servers, we increasingly struggle with loading times. Every browser has a maximum number of simultaneous persistent connections per server/proxy, especially for HTTP/1.1. With HTTP/2 support, we can finally kiss this problem goodbye.</p>\n<p>So where do we start? Do you remember this basic Node.js server example from every tutorial on web ever? Yep, this one:</p>\n<pre><code>const http = require('http');\n\nhttp.createServer(function (req, res) {\n  res.write('Hello World!');\n  res.end();\n}).listen(3000);\n</code></pre>\n<p>With Node.js 10, we get a new http2 module allowing us to use HTTP/2.0! Finally!</p>\n<pre><code>const http = require('http2');\nconst fs = require('fs');\n\nconst options = {\n  key: fs.readFileSync('example.key'),\n  cert: fs.readFileSync('example.crt')\n };\n\nhttp.createSecureServer(options, function (req, res) {\n  res.write('Hello World!');\n  res.end();\n}).listen(3000);\n</code></pre>\n<p>Full HTTP/2 support in Node.js 10 is what we have all been waiting for</p>\n<h2>With these new features, the future of Node.js is bright</h2>\n<p>The new Node.js features bring fresh air to our tech ecosystem. They open up completely new possibilities for Node.js. Have you ever imagined that this technology could one day be used for image processing or data science? Neither have I.</p>\n<p>Node latest version gives us even more long-awaited features such as support for es modules (still experimental, though) or changes to fs methods, which finally use promises rather than callbacks.</p>\n<p>Want even more new Node.js features? Watch this short video.</p>\n<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/FuWZeUfaI4s\" frameborder=\"0\" allow=\"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>\n<p>As you can see from the chart below, the popularity of Node.js seems to have peaked in early 2017, after years and years of growth. It’s not really a sign of slowdown, but rather of  maturation of this technology.</p>\n<p><img src=\"//images.ctfassets.net/xmu5vdhtphau/1ewCUNO1n9x3cbpr1t40MH/4a9333a7554affd42bffad3bcaa4b082/node-popularity-over-the-years-chart-1024x425.png\" alt=\"node-popularity-over-the-years-chart-1024x425\">\nPopularity of Node.js over time chart, peaked in 2017</p>\n<p>However, I can definitely see how all of these new improvements, as well as the growing popularity of Node.js blockchain apps (based on the truffle.js framework), may give Node.js a further boost so that it can blossom again – in new types of projects, roles and circumstances.</p>\n<p>With the release of Node.js 14, the future is looking brighter and brighter for Node.js development!</p>"}},"categories":[{"name":"Tutorials","slug":"tutorials"},{"name":"Node.js","slug":"node-js"}]}},{"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"}]}},{"node":{"slug":"11-simple-npm-tricks-that-will-knock-your-wombat-socks-off","title":"11 Simple npm Tricks That Will Knock Your Wombat Socks Off","image":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/192NyfRtbUtQpMtP9JYYZV/462bac50e7028a042ced07e97434a30e/8-min.jpg","fileName":"8-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<p>Using npm effectively can be difficult. There are a ton of features built-in, and it can be a daunting task to try to approach learning them.</p>\n<p>Personally, even learning and using just one of these tricks (<code>npm prune</code>, which is #4) saved me from getting rid of unused modules manually by deleting <code>node_modules</code> and re-installing <em>everything</em> with <code>npm install</code>. As you can probably imagine, that was insanely stressful.</p>\n<p>We've compiled this list of 11 simple-to-use npm tricks that will allow you to speed up development using npm, no matter what project you're working on.</p>\n<h2>1. Open a package’s homepage</h2>\n<p><strong>Run:</strong> <code>npm home $package</code></p>\n<p>Running the <code>home</code> command will open the homepage of the package you're running it against. Running against the <code>lodash</code> package will bring you to the Lodash website. This command can run without needing to have the package installed globally on your machine or within the current project.</p>\n<h2>2. Open package’s GitHub repo</h2>\n<p><strong>Run:</strong> <code>npm repo $package</code></p>\n<p>Similar to <code>home</code>, the <code>repo</code> command will open the GitHub repository of the package you're running it against. Running against the <code>express</code> package will bring you to the official Express repo. Also like <code>home</code>, you don’t need to have the package installed.</p>\n<h2>3. Check a package for outdated dependencies</h2>\n<p><strong>Run:</strong> <code>npm outdated</code></p>\n<p>You can run the <code>outdated</code> command within a project, and it will check the npm registry to see if any of your packages are outdated. It will print out a list in your command line of the current version, the wanted version, and the latest version.</p>\n<p><img src=\"https://nodesource.com/media/2016/Aug/Screen_Shot_2016_08_26_at_3_52_53_PM-1472242056432.png\" alt=\"Running npm outdated on a Node project\"></p>\n<h2>4. Check for packages not declared in package.json</h2>\n<p><strong>Run:</strong> <code>npm prune</code></p>\n<p>When you run <code>prune</code>, the npm CLI will run through your <code>package.json</code> and compare it to your project’s <code>/node_modules</code> directory. It will print a list of modules that aren’t in your <code>package.json</code>.</p>\n<p>The <code>npm prune</code> command then strips out those packages, and removes any you haven't manually added to <code>package.json</code> or that were <code>npm install</code>ed without using the <code>--save</code> flag.</p>\n<p><img src=\"https://nodesource.com/media/2016/Aug/Screen_Shot_2016_08_26_at_3_54_00_PM-1472242073013.png\" alt=\"Running npm prune on a Node project\"></p>\n<p><strong>Update:</strong> Thanks to <a href=\"https://twitter.com/EvanHahn\">@EvanHahn</a> for noticing a personal config setting that made <code>npm prune</code> provide a slightly different result than the default <code>npm</code> would provide!</p>\n<h2>5. Lock down your dependencies versions</h2>\n<p><strong>Run:</strong> <code>npm shrinkwrap</code></p>\n<p>Using <code>shrinkwrap</code> in your project generates an <code>npm-shrinkwrap.json</code> file. This allows you to pin the dependencies of your project to the specific version you’re currently using within your <code>node_modules</code> directory. When you run <code>npm install</code> and there is a <code>npm-shrinkwrap.json</code> present, it will override the listed dependencies and any semver ranges in <code>package.json</code>.</p>\n<p>If you need verified consistency across <code>package.json</code>, <code>npm-shrinkwrap.json</code> and <code>node_modules</code> for your project, you should consider using <a href=\"https://github.com/uber/npm-shrinkwrap\">npm-shrinkwrap</a>.</p>\n<p><img src=\"https://nodesource.com/media/2016/Aug/Screen_Shot_2016_08_26_at_3_54_36_PM-1472242098179.png\" alt=\"Running npm shrinkwrap on a Node project\"></p>\n<h2>6. Use npm v3 with Node.js v4 LTS</h2>\n<p><strong>Run:</strong> <code>npm install -g npm@3</code></p>\n<p>Installing <code>npm@3</code> globally with npm will update your npm v2 to npm v3, including on the Node.js v4 LTS release (“Argon”) ships with the npm v2 LTS release. This will install the latest stable release of npm v3 within your v4 LTS runtime.</p>\n<h2>7. Allow <code>npm install -g</code> without needing <code>sudo</code></h2>\n<p><strong>Run:</strong> <code>npm config set prefix $dir</code></p>\n<p>After running the command, where <code>$dir</code> is the directory you want npm to <em>install your global modules to</em>, you won’t need to use sudo to install modules globally anymore. The directory you use in the command becomes your global bin directory. </p>\n<p>The only caveat: you will need to make sure you <strong>adjust your user permissions</strong> for that directory with <code>chown -R $USER $dir</code> and you <strong>add</strong> <code>$dir/bin</code> to your PATH.</p>\n<h2>8. Change the default save prefix for all your projects</h2>\n<p><strong>Run:</strong> <code>npm config set save-prefix=\"~\"</code></p>\n<p>The tilde (<code>~</code>) is more conservative than what npm defaults to, the caret (<code>^</code>), when installing a new package with the <code>--save</code> or <code>--save-dev</code> flags. The tilde pins the dependency to the minor version, allowing patch releases to be installed with <code>npm update</code>. The caret pins the dependency to the major version, allowing minor releases to be installed with <code>npm update</code>.</p>\n<h2>9. Strip your project's <code>devDependencies</code> for a production environment</h2>\n<p>When your project is ready for production, make sure you install your packages with the added <code>--production</code> flag. The <code>--production</code> flag installs your <code>dependencies</code>, ignoring your <code>devDependencies</code>. This ensures that your development tooling and packages won’t go into the production environment.</p>\n<p>Additionally, you can set your <code>NODE_ENV</code> environment variable to <code>production</code> to ensure that your project’s <code>devDependencies</code> are never installed.</p>\n<h2>10. Be careful when using <code>.npmignore</code></h2>\n<p>If you haven't been using <code>.npmignore</code>, it defaults to <code>.gitignore</code> with a few additional sane defaults.</p>\n<p>What many don't realize that once you add a <code>.npmignore</code> file to your project the <code>.gitignore</code> rules are (ironically) ignored. The result is you will need to audit the two ignore files in sync to prevent sensitive leaks when publishing.</p>\n<h2>11. Automate <code>npm init</code> with defaults</h2>\n<p>When you run <code>npm init</code> in a new project, you’re able to go through and set up your <code>package.json</code>’s details. If you want to set defaults that <code>npm init</code> will always use, you can use the <code>config set</code> command, with some extra arguments:</p>\n<pre><code>npm config set init.author.name $name\nnpm config set init.author.email $email\n</code></pre>\n<p>If, instead, you want to completely customize your init script, you can point to a self-made default init script by running </p>\n<pre><code>npm config set init-module ~/.npm-init.js`\n</code></pre>\n<p>Here’s a sample script that prompts for private settings and creates a GitHub repo if you want. Make sure you change the default GitHub username (<code>YOUR_GITHUB_USERNAME</code>) as the fallback for the GitHub username environment variable.</p>\n<pre><code class=\"language-js\">var cp = require('child_process');\nvar priv;\n\nvar USER = process.env.GITHUB_USERNAME || 'YOUR_GITHUB_USERNAME';\n\nmodule.exports = {\n\n  name: prompt('name', basename || package.name),\n\n  version: '0.0.1',\n\n  private: prompt('private', 'true', function(val){\n    return priv = (typeof val === 'boolean') ? val : !!val.match('true')\n  }),\n\n  create: prompt('create github repo', 'yes', function(val){\n    val = val.indexOf('y') !== -1 ? true : false;\n\n    if(val){\n      console.log('enter github password:');\n      cp.execSync(\"curl -u '\"+USER+\"' https://api.github.com/user/repos -d \" +\n        \"'{\\\"name\\\": \\\"\"+basename+\"\\\", \\\"private\\\": \"+ ((priv) ? 'true' : 'false')  +\"}' \");\n      cp.execSync('git remote add origin '+ 'https://github.com/'+USER+'/' + basename + '.git');\n    }\n\n    return undefined;\n  }),\n\n  main: prompt('entry point', 'index.js'),\n\n  repository: {\n    type: 'git',\n    url: 'git://github.com/'+USER+'/' + basename + '.git' },\n\n  bugs: { url: 'https://github.com/'+USER'/' + basename + '/issues' },\n\n  homepage: \"https://github.com/\"+USER+\"/\" + basename,\n\n  keywords: prompt(function (s) { return s.split(/\\s+/) }),\n\n  license: 'MIT',\n\n  cleanup: function(cb){\n\n    cb(null, undefined)\n  }\n\n}\n</code></pre>\n<br />\n# One last thing...\n<p>If you want to learn more about npm, Node.js, JavaScript, Docker, Kubernetes, Electron, and tons more, you should follow <a href=\"https://twitter.com/nodesource\">@NodeSource</a> on Twitter. We're always around and would love to hear from you!</p>"}},"categories":[{"name":"Tutorials","slug":"tutorials"},{"name":"Node.js","slug":"node-js"}]}}]},"contentfulHero":{"headLine":"List of useful articles and blog post on Node.js","coverImage":{"file":{"url":"//images.ctfassets.net/xmu5vdhtphau/3tCG630sR3116gwqT52u9C/dadf240e71f8ab06e2492da2e46a561a/blog-min.jpg","fileName":"blog-min.jpg"}}}},"pageContext":{"limit":7,"skip":7,"numPages":5,"currentPage":2,"type":"blog","hero":"hero-blogs","prevPath":"/blogs","nextPath":"/blogs/page/3"}}}