<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Osio Labs on Medium]]></title>
        <description><![CDATA[Stories by Osio Labs on Medium]]></description>
        <link>https://medium.com/@osiolabs?source=rss-1a9b50f5b873------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ws6LcPM5gYWRMu0Lig1XGA.png</url>
            <title>Stories by Osio Labs on Medium</title>
            <link>https://medium.com/@osiolabs?source=rss-1a9b50f5b873------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:56:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@osiolabs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Validate and Sanitize an ExpressJS Form]]></title>
            <link>https://medium.com/@osiolabs/how-to-validate-and-sanitize-an-expressjs-form-fc2ee97b9988?source=rss-1a9b50f5b873------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc2ee97b9988</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Osio Labs]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 18:47:57 GMT</pubDate>
            <atom:updated>2020-09-25T18:47:57.706Z</atom:updated>
            <content:encoded><![CDATA[<p>By <a href="https://www.youtube.com/channel/UC-gCUMK_EGUqJ7P9VA7BJmQ/featured">Coding Commanders</a> for <a href="https://heynode.com/">Hey Node</a></p><p>When a web application accepts user input, you never know what data to expect. The form data may be invalid or even hazardous. The erroneous data may be due to a user making an unintentional mistake or a malicious hacker implementing an attack. Either way, validation and sanitization protect your Node.js application against inappropriate input.</p><p>In this tutorial, we’ll:</p><ul><li>Install the express-validator library for use with an ExpressJS server</li><li>Validate user input from a login form</li><li>Sanitize user input from a login form</li><li>Return validation errors to the user to improve the UX</li></ul><p>By the end of this tutorial, you will know how to use <a href="https://express-validator.github.io/docs/index.html">express-validator</a> to perform back-end validation and data sanitation.</p><h3>Goal</h3><p>Use the express-validator library to validate and sanitize a login form.</p><h3>What is express-validator?</h3><p>Express-validator is a library used to validate and sanitize ExpressJS forms. It is based on <a href="https://github.com/validatorjs/validator.js">validator.js</a> and allows you to:</p><ul><li>Utilize existing validation functions</li><li>Create custom validation conditions</li><li>Apply form sanitization functions</li><li>Design unique error messages</li></ul><h3>Why use express-validator?</h3><p>It is a flexible and straightforward way to manage necessary form validation and sanitization. Although you can write your own code, it would take a lot of time, and you would need a lot of practice to ensure you didn’t miss anything. The express-validator library is also widely used and accepted by the community.</p><h3>Validate and sanitize a login form</h3><p>In the previous tutorial, we created a login form using ExpressJS. In this tutorial, we will use express-validator to validate and sanitize the user input on our login form.</p><p>Here is the login code that we will add validation to, in the file <em>/static/login.html</em>:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>	&lt;title&gt;Example Login Form&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>	&lt;form action=&quot;/login&quot; method=&quot;post&quot;&gt;<br>  	&lt;!-- user input--&gt;<br>  	Username:&lt;br&gt;<br>  	&lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;Username&quot; required&gt;&lt;br&gt;&lt;br&gt;<br>  	Password:&lt;br&gt;<br>  	&lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;Password&quot; required&gt;&lt;br&gt;&lt;br&gt;<br>  	&lt;!-- submit button --&gt;<br>  	&lt;input type=&quot;submit&quot; value=&quot;login&quot;&gt;<br>	&lt;/form&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>And the corresponding <em>server.js</em>:</p><pre>const express = require(&#39;express&#39;). // Include ExpressJS<br>const app = express(). // Create an ExpressJS app<br>const bodyParser = require(&#39;body-parser&#39;); // Middleware</pre><pre>app.use(bodyParser.urlencoded({ extended: false }));</pre><pre>// Route to Homepage<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.sendFile(__dirname + &#39;/static/index.html&#39;);<br>});</pre><pre>// Route to Login Page<br>app.get(&#39;/login&#39;, (req, res) =&gt; {<br>  res.sendFile(__dirname + &#39;/static/login.html&#39;);<br>});</pre><pre>app.post(&#39;/login&#39;, (req, res) =&gt; {<br>  // Insert Login Code Here<br>  let username = req.body.username;<br>  let password = req.body.password;<br>  res.send(`Username: ${username} Password: ${password}`);<br>});</pre><pre>const port = 3000 // Port we will listen on</pre><pre>// Function to listen on the port<br>app.listen(port, () =&gt; console.log(`This app is listening on port ${port}`));</pre><p>I assume you either followed the previous tutorial or have created an ExpressJS form on your own. Thus, you already have NodeJS and ExpressJS installed. If you do not have a functional ExpressJS form, please <a href="https://heynode.com/tutorial/process-user-login-form-expressjs">review the previous tutorial</a>.</p><h3>Install express-validator</h3><p>Install the package with the following npm command:</p><pre>npm install express-validator</pre><h3>Include express-validator functions</h3><p>Add the following to the top of your <em>server.js</em>:</p><pre>// Include Express Validator Functions<br>const { check, validationResult } = require(&#39;express-validator&#39;);</pre><ol><li>check is the primary function used to validate and sanitize input. It takes in 2 optional parameters:</li></ol><ul><li><strong>field:</strong> The field parameter can be a string or an array of strings representing the input fields you want to check. If there is no field value, the <a href="https://express-validator.github.io/docs/whole-body-validation.html">entire request object</a> will get checked.</li><li><strong>message:</strong> The message parameter holds a string that contains a custom error message. If there is no message value, the default message is “Invalid value”.</li></ul><ol><li>validationResult is a function of the body request object (req) and is used to return an object containing all validation errors.</li></ol><h3>Identify rules for input fields</h3><p>Before you write the validation code, you must identify what criteria the input must meet. For our example login page, let’s say:</p><ol><li>username:</li></ol><ul><li>A valid email address</li></ul><ol><li>password:</li></ol><ul><li>At least 8 characters</li><li>Contains a number</li><li>Contains a capital letter</li></ul><h3>Choose validation methods</h3><p>Now that we know which rules to check for, we must identify the appropriate validator methods to use. You may do so by using the <a href="https://express-validator.github.io/docs/index.html">express-validator</a> documentation or the complete list in the <a href="https://github.com/validatorjs/validator.js#validators">validator.js</a> docs.</p><p>To check that the username is a valid email address we will use isEmail(). If the username input is not an email address, we will use the error message &#39;Username Must Be an Email Address&#39;.</p><pre>check(&#39;username&#39;, &#39;Username Must Be an Email Address&#39;).isEmail()</pre><p>To check that the password is at least 8 characters, we use isLength(). If the password input is less than 8 characters, the error message is &#39;Password Must Be at Least 8 characters&#39;. Instead of taking the message in as a parameter to the check function, we will use withMessage(). Doing so allows us to use a different error message for each possible password validation error.</p><pre>check(&#39;password&#39;).isLength({ min: 8 }).withMessage(&#39;Password Must Be at Least 8 Characters&#39;)</pre><p>To check that the password contains a number and to check that it includes an uppercase letter, we use .matches().</p><pre>.matches(&#39;[0-9]&#39;).withMessage(&#39;Password Must Contain a Number&#39;)<br>.matches(&#39;[A-Z]&#39;).withMessage(&#39;Password Must Contain an Uppercase Letter&#39;)</pre><h3>Add validation to app.post</h3><p>Insert an array of check functions as a parameter of the app.post function. In the example below, we store our validation array in a variable called loginValidate.</p><pre>// Validation rules.<br>var loginValidate = [<br>  check(&#39;username&#39;, &#39;Username Must Be an Email Address&#39;).isEmail(),<br>  check(&#39;password&#39;).isLength({ min: 8 })<br>  .withMessage(&#39;Password Must Be at Least 8 Characters&#39;)<br>  .matches(&#39;[0-9]&#39;).withMessage(&#39;Password Must Contain a Number&#39;)<br>  .matches(&#39;[A-Z]&#39;).withMessage(&#39;Password Must Contain an Uppercase Letter&#39;)];</pre><pre>// Process user input.<br>app.post(&#39;/login&#39;, loginValidate, (req, res) =&gt; {<br>  // Insert Login Code Here<br>});</pre><h3>Add sanitation</h3><p>In this project, we use 3 sanitization methods:</p><ol><li>trim() trims characters from input. By default (with no parameters) this method trims whitespace.</li><li>escape() will replace certain characters (i.e. &lt;, &gt;, /, &amp;, &#39;, &quot;) with the corresponding HTML entity.</li><li>normalizeEmail() ensures the email address is in a safe and standard format.</li></ol><p>To see a full list of sanitization options visit the <a href="https://github.com/validatorjs/validator.js#sanitizers">sanitization section</a> of validator.js’s documentation.</p><p>We add all 3 sanitizers to our check of the username.</p><pre>check(&#39;username&#39;, &#39;Username Must Be an Email Address&#39;).isEmail().trim().escape().normalizeEmail()</pre><p>We add trim() and escape() to our check of the password.</p><pre>check(&#39;password&#39;).isLength({ min: 8 })<br>.withMessage(&#39;Password Must Be at Least 8 Characters&#39;)<br>.matches(&#39;[0-9]&#39;).withMessage(&#39;Password Must Contain a Number&#39;)<br>.matches(&#39;[A-Z]&#39;).withMessage(&#39;Password Must Contain an Uppercase Letter&#39;)<br>.trim().escape()</pre><p>Our validation array should now look like this:</p><pre>var loginValidate = [<br>  // Check Username<br>  check(&#39;username&#39;, &#39;Username Must Be an Email Address&#39;).isEmail().trim().escape().normalizeEmail(),<br>  // Check Password<br>  check(&#39;password&#39;).isLength({ min: 8 }).withMessage(&#39;Password Must Be at Least 8 Characters&#39;).matches(&#39;[0-9]&#39;).withMessage(&#39;Password Must Contain a Number&#39;).matches(&#39;[A-Z]&#39;).withMessage(&#39;Password Must Contain an Uppercase Letter&#39;).trim().escape()];</pre><h3>Check for errors</h3><p>Inside our app.post’s callback function. we declare a variable called errors and set it equal to validationResult(req).</p><pre>const errors = validationResult(req);</pre><p>Next, we create an if statement. If there are validation errors, we want to display them to the user. If there are no errors, the application continues as normal. If the user input is all valid, our example application displays the inputted username and password.</p><p>To return the error result object we can choose from 2 methods:</p><ol><li>array() is the method used in the example below. It returns an array of <strong>all</strong> validation errors.</li><li>mapped() will return an array containing only the first validation error for each field.</li></ol><pre>// Process User Input<br>app.post(&#39;/login&#39;, loginValidate, (req, res) =&gt; {<br>	const errors = validationResult(req);<br>	if (!errors.isEmpty()) {<br>    return res.status(422).json({ errors: errors.array() });<br>	}<br>	else {<br>    // Insert Login Code Here<br>    let username = req.body.username;<br>    let password = req.body.password;<br>    res.send(`Username: ${username} Password: ${password}`);<br>	}<br>});</pre><p>Let’s say the user broke every input rule. The list of errors would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*qiW7F7bF8ZWvEDll.png" /></figure><p>If there are no errors, you should see something like this:</p><pre>Username: candy@cane.com Password: Wkdi98rs!1</pre><h3>Final server.js code</h3><p>Now that we have finished writing the validation and sanitization code, <em>server.js</em> should look like this:</p><pre>const express = require(&#39;express&#39;). // Include ExpressJS<br>const app = express(). // Create an ExpressJS app<br>const bodyParser = require(&#39;body-parser&#39;); // Middleware</pre><pre>// Include Express Validator Functions<br>const { check, validationResult } = require(&#39;express-validator&#39;);</pre><pre>app.use(bodyParser.urlencoded({ extended: false }));</pre><pre>// Route to Homepage<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.sendFile(__dirname + &#39;/static/index.html&#39;);<br>});</pre><pre>// Route to Login Page<br>app.get(&#39;/login&#39;, (req, res) =&gt; {<br>  res.sendFile(__dirname + &#39;/static/login.html&#39;);<br>});<br>// Validation Array<br>var loginValidate = [<br>  // Check Username<br>  check(&#39;username&#39;, &#39;Username Must Be an Email Address&#39;).isEmail()<br>  .trim().escape().normalizeEmail(),<br>  // Check Password<br>  check(&#39;password&#39;).isLength({ min: 8 }).withMessage(&#39;Password Must Be at Least 8 Characters&#39;).matches(&#39;[0-9]&#39;).withMessage(&#39;Password Must Contain a Number&#39;).matches(&#39;[A-Z]&#39;).withMessage(&#39;Password Must Contain an Uppercase Letter&#39;).trim().escape()];</pre><pre>/. Process User Input<br>app.post(&#39;/login&#39;, loginValidate, (req, res) =&gt; {<br>  const errors = validationResult(req);<br>  if (!errors.isEmpty()) {<br>  	return res.status(422).json({ errors: errors.array() });<br>  }<br>  else {<br>. // Insert Login Code Here<br>. let username = req.body.username;<br>. let password = req.body.password;<br>. res.send(`Username: ${username} Password: ${password}`);<br>  }<br>});</pre><pre>const port = 3000// Port we will listen on</pre><pre>// Function to listen on the port<br>app.listen(port, () =&gt; console.log(`This app is listening on port ${port}`));</pre><h3>Recap</h3><p>It is essential to validate and sanitize user input. The express-validator library makes it easy to implement standard and custom validation and sanitization. The check function implements conditions, and the validationResult function accesses validation errors.</p><p>An array of check functions get passed into app.post() and validationResult() is used inside app.post()&#39;s callback.</p><p><strong>See the full series by @codingcommander on User Authentication in Node.js Applications at </strong><a href="https://heynode.com/"><strong>Hey Node</strong></a><strong>.</strong></p><figure><img alt="Hey Node logo" src="https://cdn-images-1.medium.com/max/1024/1*1MAjjoyLK7uC5k-nAVIJbQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc2ee97b9988" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Express.js 5: Node’s Latest Web Framework Release]]></title>
            <link>https://medium.com/@osiolabs/express-js-5-nodes-latest-web-framework-release-83a7b00c0f77?source=rss-1a9b50f5b873------2</link>
            <guid isPermaLink="false">https://medium.com/p/83a7b00c0f77</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Osio Labs]]></dc:creator>
            <pubDate>Fri, 07 Aug 2020 19:54:41 GMT</pubDate>
            <atom:updated>2020-08-07T19:54:41.894Z</atom:updated>
            <content:encoded><![CDATA[<p>by <a href="https://twitter.com/jonchurch">Jon Church</a></p><p>A new major version of Express.js is coming, the first major version bump since Express 4 was released in April of 2014. Although Express 5 is a major version change in the <a href="https://semver.org/">SemVer</a> sense, the Node.js framework remains largely the same. Much of what’s changed is centered around removing function signatures, which were deprecated in Express 4. You won’t have to relearn much to continue to work with Express 5.</p><p>This version has been under development for a long time, and contains a lot of maintenance-related updates that could only be done in a major version (like breaking dependency updates, removing deprecated features, etc). One of the goals of 5 is to resolve overdue updates to allow for the possibility of bigger changes in the future.</p><p>That caveat aside, here are some of the notable changes coming to Express 5:</p><ul><li><a href="https://heynode.com/blog/2020-08/expressjs-5-nodes-latest-web-framework-release#route-matching-changes">Route Matching Changes</a></li><li><a href="https://heynode.com/blog/2020-08/expressjs-5-nodes-latest-web-framework-release#async-middleware-and-route-handlers">Async Middleware/Route Handlers</a></li><li><a href="https://heynode.com/blog/2020-08/expressjs-5-nodes-latest-web-framework-release#default-to-simple-query-parser-setting">Default to Simple Query Parser Setting</a></li><li><a href="https://heynode.com/blog/2020-08/expressjs-5-nodes-latest-web-framework-release#remove-deprecated-features">Remove Deprecated Features</a></li><li><a href="https://heynode.com/blog/2020-08/expressjs-5-nodes-latest-web-framework-release#community-updates">Community Updates</a></li></ul><p>There isn’t exactly an ETA on Express 5’s release, but by the end of 2020 is a very safe estimate. However, you can try out the latest release by running npm i express@next. You can also keep an eye on the <a href="https://github.com/expressjs/express/pull/2237">tracking pull request for 5</a>.</p><h3>Route Matching Changes</h3><p>Express 5’s router upgraded to <a href="https://github.com/pillarjs/path-to-regexp/blob/master/History.md#200--2017-08-23">path-to-regexp@2.x</a>, which brings changes to path matching:</p><ul><li>RegExp special characters can now only be used in a parameter, as opposed to anywhere.</li><li>No wildcard asterisk * -- use parameters instead ((.*) or :splat*) Migrating use of wildcards would look like the following:</li></ul><p>// v4 code app.get(&quot;*&quot;, (req, res) =&gt; {}); // Matches /, /foo, /foo/bar, etc app.get(&quot;/foo/*/baz&quot;, (req, res) =&gt; {}); // Matches /foo/bar/baz, /foo/qux/baz, etc // Equivalent v5 code app.get(&quot;(.*)&quot;, (req, res) =&gt; {}); app.get(&quot;/foo/(.*)/baz&quot;, (req, res) =&gt; {});</p><p>Explicit trailing slash</p><ul><li>/foo/ will match only /foo/ and nothing else</li><li>For old behavior use /foo instead.</li></ul><p>Parameters can have suffixes to augment meaning and affect how matching works:</p><ul><li>*: <a href="https://github.com/pillarjs/path-to-regexp#zero-or-more">Zero or more</a>, e.g. /:foo* matches /bar/baz/qux and /</li><li>+: <a href="https://github.com/pillarjs/path-to-regexp#one-or-more">One or more</a>, e.g. /:foo+ matches /bar and /bar/baz but not /</li><li>?: <a href="https://github.com/pillarjs/path-to-regexp#optional">Optional</a>, e.g. /:foo/:bar? matches /baz and /baz/qux</li></ul><h3>Async Middleware and Route Handlers</h3><p>It was common under Express 4 for users to rely on packages such as <a href="https://www.npmjs.com/package/express-async-handler">express-async-handler</a> or create their own helper functions to catch rejections of handlers that returned promises. Express 5 will properly handle rejected promises returned from middleware functions and route handlers, passing the rejection on to your error handler.</p><p>Express 4 ignores the rejection of the Promise implicitly returned from this async function:</p><pre>app.use(async (req, res, next) =&gt; {<br>  throw new Error(&quot;BOOM!&quot;);<br>});</pre><p>The above is equivalent to returning a Promise explicitly from a middleware or route handler:</p><pre>app.use((req, res, next) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    reject(new Error(&quot;BOOM&quot;));<br>  });<br>});</pre><p>Express 5 will handle rejections from Promises returned from middleware or route handlers by passing the rejection as the first argument to next.</p><p>This allows you to refactor code that looks like this:</p><pre>function willThrow() {<br>  throw new Error(&quot;BOOM&quot;);<br>}</pre><pre>// Express v4<br>router.get(&quot;/test&quot;, async (req, res, next) =&gt; {<br>  try {<br>    await willThrow();<br>    res.send(&quot;okay&quot;);<br>  } catch (err) {<br>    next(err);<br>  }<br>});</pre><p>into this:</p><pre>function willThrow() {<br>  throw new Error(&quot;BOOM&quot;);<br>}</pre><pre>// Express v5<br>router.get(&quot;/test&quot;, async (req, res) =&gt; {<br>  await willThrow();<br>  res.send(&quot;okay&quot;);<br>});</pre><h3>Default to Simple Query Parser Setting</h3><p>Query parsing will no longer use the extended option by default. It will default to simple. Extended query parsing allows you to use nested query parameters, e.g. /url?a[0]=b&amp;a[1]=c. It uses the <a href="https://www.npmjs.com/package/qs">qs</a> library for parsing.</p><p>To opt back in to extended query parsing:</p><pre>app.set(&quot;query parser&quot;, &quot;extended&quot;);</pre><p>Simple query parsing instead uses Node.js’ <a href="https://nodejs.org/api/querystring.html">querystring</a> module, and does not support nesting parameters.</p><h3>Remove Deprecated Features</h3><p>There are a host of features which were marked as deprecated in Express 4; using them would print a deprecation warning to the console. Most have been deprecated for several years.</p><p>These deprecated features have been removed in Express 5. They are almost entirely outdated function signatures, e.g. res.json(status, body), which were superseded in the Express 4 line by res.status(status).json(body). You can see the entire list in the <a href="https://github.com/expressjs/express/blob/5.0/History.md">History</a> file, where they&#39;re noted with remove.</p><p>If your app doesn’t currently print Express deprecation warnings, you shouldn’t be affected by these changes.</p><h3>Community Updates</h3><p>Express became part of the <a href="https://openjsf.org/">OpenJS Foundation (OpenJSF)</a> in 2019, joining projects such as Node.js, Electron, lodash, webpack, nvm, and many others. The OpenJSF has worked with Express to improve its governance and code of conduct, and generally provided support for the community of maintainers.</p><p>If you’re interested in what’s happening in Express, you can follow along with the <a href="https://github.com/expressjs/discussions">Technical Committee discussions</a> and also catch up by watching <a href="https://www.youtube.com/channel/UCYjxjAeH6TRik9Iwy5nXw7g/videos">recordings of past meetings</a>.</p><p>For several years Express has been maintained by a small group of very dedicated volunteers, but in 2020 the Express contributor community has been growing. Part of that growth is a Triage team, started with the help of the <a href="https://github.com/nodejs/package-maintenance">Node.js Package Maintenance Working Group</a>. The Package Maintenance WG aims to improve the lives of maintainers in the Node ecosystem. Express’ triage initiative is a pilot project in partnership with the working group. Since kicking off in late 2019, it has seen a lot of success and offered new Express contributors a way to get involved.</p><p>The Triage team helps the maintainers manage issues and pull requests by reviewing, labeling, asking for more information, answering questions, and reproducing bugs. The goal is not just to relieve the maintainers of some repetitive work, but also to get more people up to speed to contribute to the packages that make up Express.</p><p>Packages like express, multer, and express-session are not only downloaded millions of times a month, but are an entry point into the ecosystem for many new Node.js developers. That means the issue trackers see a lot of activity, thus creating work for maintainers and contribution opportunities for the Triage team.</p><p>Bringing on dedicated contributors is an important part of Express’s long-term health. It can be difficult to start contributing to a project as large as Express, but the Triage team is an important new development for getting new people acclimated to the project. With more contributors who are committed to working on Express long term, we can hopefully see the next version released sooner than the 6 years it took for Express 5 to be completed!</p><p>If you’re interested in joining the Triage team you can read the <a href="https://github.com/expressjs/express/blob/master/Triager-Guide.md">Triager Guide</a> to see what it involves, and following these <a href="https://github.com/expressjs/express/blob/master/Contributing.md#becoming-a-triager">instructions</a> to apply.</p><p>If you enjoyed this post, <a href="https://heynode.com/signup">sign up for our newsletter</a> to get notified of new content.</p><p><strong>Learn Node.js</strong><br>Access all our written and video Node.js tutorials.</p><p><a href="https://members.osiolabs.com/user/register?destination=/oauth/authorize%3Fclient_id%3D501a6854-dbbf-43a9-91b8-94eb5aa24897%26redirect_uri%3Dhttps%253A%252F%252Fheynode.com%252Fblog%252F2020-08%252Fexpressjs-5-nodes-latest-web-framework-release%252F%26response_type%3Dcode%26state%3D%257B%257D">Sign up</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83a7b00c0f77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shortening the Work Week Amidst a Pandemic]]></title>
            <link>https://medium.com/@osiolabs/shortening-the-work-week-amidst-a-pandemic-ea1bea143bed?source=rss-1a9b50f5b873------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1bea143bed</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[pandemic]]></category>
            <dc:creator><![CDATA[Osio Labs]]></dc:creator>
            <pubDate>Mon, 08 Jun 2020 19:46:55 GMT</pubDate>
            <atom:updated>2020-06-08T19:48:01.655Z</atom:updated>
            <content:encoded><![CDATA[<p>by <a href="https://twitter.com/add1sun">Addison Berry</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9FdSbtvBMTbYtthjzprmg.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@charlesdeluvio">Charles Deluvio</a> on Unsplash</figcaption></figure><p>Because <a href="https://osiolabs.com/">Osio Labs</a> is a distributed company, we have a lot of experience working remotely. We’re efficient at it. But like so many people around the world, our lives have dramatically changed. Working from home in the pandemic is entirely different. Tutorial bugs still have to be fixed, but infants also need childcare. Teenagers need encouragement to come out of their rooms once in a while, and partners need help with their new work environment. Not to mention the fact that we simply need to process what in the bleep is going on in the world.</p><h3>A three-legged race with a drunk</h3><p>During a recent sprint meeting, one of my teammates described his efforts to fix a stubborn bug on <a href="https://drupalize.me/">Drupalize.Me</a>. It was a journey fraught with distractions that only this pandemic could have conjured up, including his new additional job as a second-grade teacher. He described working on this bug as running a three-legged race with a drunk. What better description could there be of what working during a pandemic has become? Tasks no longer get accomplished in a straight and easy line. Work routines have been replaced with nervous dashes to the grocery store, tug-of-war kid duty with spouses, and making space for partners newly working from home. And all this while trying to keep general anxiety under control.</p><h3>Distracted, anxious, more distracted</h3><p>Personally, my ramped-up anxiety means I can’t focus the way I usually do. I am completely and utterly distracted by the world around me and worrying about my (high-risk) family. Insomnia is draining me mentally and physically. It’s all taking its toll, snowballing into feeling guilty about my work output, or lack thereof. For example, it has taken me almost a month to write this one blog post. I’m stuck in a vicious cycle where it’s hard to feel productive and energized, which makes me anxious, which in turn exhausts me, etc.</p><p>As a CEO, while I’m worried about managing the economic impact of these unprecedented times, my biggest concern and stressor has been properly addressing the mental health needs of my team. What can I do to help? The work — the daily business of Osio Labs — is what we get paid for. Still, business is all about people, and people need to be happy, healthy, and functional. As a company, this is how we’ve built a robust and successful team. As a leader, this is always my top responsibility.</p><h3>80% is okay</h3><p>By March, the reality of the situation was becoming apparent. I shared with the team that we should recognize this for the bizarre experience it was and reinforced that they should make free use of their personal days. By the end of March, I came to the conclusion that we needed to more directly address the fundamental reality we are in. The line between our work and personal lives is now totally blurred. We were on a course towards frustration and burnout. My teammates and I have had to acknowledge that the distraction this pandemic has imposed on our lives is making us less productive.</p><p>Because we need to give that distraction room to breathe, we agreed to adjust our work-week to four days, while still keeping salaries at 100%. We changed our team goals to focus only on the top priorities, giving ourselves permission to say no to some projects and tasks. We gave ourselves an extra day (or two half-days) in the week to address the challenges of this extraordinary time.</p><h3>Leaning into our values</h3><p>We’ve never done anything like this before. As I’ve reflected on our decision, I’ve realized that it was in fundamental keeping with our core, open-source-based values, especially building trust. Businesses are built on relationships. Trust is fundamental to healthy relationships. In this case, we can be vulnerable and acknowledge how the state of the world is affecting us at work. We can communicate our needs openly, and we can all treat each other like responsible adults.</p><p>We are navigating rough seas together. Over the coming months, we’ll need to react and adjust to the effects of the pandemic on our lives. Good communication, building trust, and keeping a critical eye on our work-life balance will be more important than ever. While this year has been thrown into uncertainty in awful new ways, one thing I am sure of is that we will survive this as a team and help each and every person through it as best we can.</p><p><a href="https://osiolabs.com/">Learn more about Osio Labs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1bea143bed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is the Express Node.js Framework?]]></title>
            <link>https://medium.com/@osiolabs/what-is-the-express-node-js-framework-f831d0c36a38?source=rss-1a9b50f5b873------2</link>
            <guid isPermaLink="false">https://medium.com/p/f831d0c36a38</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[Osio Labs]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 21:37:24 GMT</pubDate>
            <atom:updated>2020-04-13T21:37:24.243Z</atom:updated>
            <content:encoded><![CDATA[<p>***<em>This tutorial introduces the entire </em><a href="https://heynode.com/"><em>Hey Node</em></a><em> series on setting up API proxy middleware with Node.js Express</em>. ***</p><p>In this tutorial we’ll learn about <a href="https://expressjs.com/">Express</a>, the free and open-source Node.js web application framework. Built on top of the Node.js built-in http module, Express helps us set up routing and handles the request/response cycle.</p><p>We’ll take a look at some of the features of Express, learn what it can offer us that the built-in HTTP modules in Node.js can’t, and explain why it’s a great tool in any Node developer’s toolbox.</p><p>By the end of this tutorial, you should be able to:</p><ul><li>Understand the benefits of working with a web framework like Express</li><li>Identify core components that make up the Express framework</li><li>Learn how Express uses middleware to extend its capabilities</li></ul><h4>Express.js overview</h4><p>The most common use for Node.js is writing Web applications, and a large percentage of these web applications today are using <a href="https://expressjs.com/">Express.js</a> as their server framework. Express can be used to create JSON APIs, Server-side rendered web applications, or Microservices.</p><p>But why? You don’t need Express to create a basic HTTP server with Node.js. You can do that using the built-in http module:</p><pre>const http = require(&quot;http&quot;);</pre><pre>const server = http.createServer((req, res) =&gt; {<br>  res.writeHead(200, { &quot;Content-Type&quot;: &quot;text/plain&quot; });<br>  res.write(&quot;Hello World&quot;);<br>  res.end(&quot;\n&quot;);<br>});</pre><pre>server.listen(8000, () =&gt; {<br>  console.log(`Server listening on port 8000`);<br>});</pre><p>This code creates a basic HTTP server that listens to requests on port 8000 and returns “Hello World”. For something that simple, you don’t need Express. But when are things that simple?</p><p>According to the Express website itself, Express is a “Fast, unopinionated, minimalist web framework for Node.js”. In our own words, Express (and the other web frameworks in the Node.js ecosystem) makes developing and maintaining a web server <em>much</em> friendlier than doing it using built-in Node.js utilities.</p><p>Express uses those built-in utilities under the hood, but provides a set of common handlers, settings, utilities, and other tools which greatly improve the experience and speed of creating a web server. The Express framework comes with the basics of what you need to get started, and doesn’t impose any strict rules on how you use those tools to create your application.</p><p>The community-supported ecosystem around Express provides countless extensions in the form of “middleware” to add any kind of functionality or help you accomplish just about any task you might want. This combination of sane defaults and common tools combined with the rich ecosystem is what has made Express the most popular server framework for Node.js.</p><h4>Core concepts in Express.js</h4><p>Most web servers do something like the following:</p><ul><li>Listen for requests that come to the server</li><li>Receive HTTP requests at an endpoint, such as /home, and parse the information sent with the request</li><li>Run code in response to the type of HTTP verb the request was made from</li><li>Respond to the request in some way</li></ul><p>When working with Express, we have tools to help us achieve these steps in only a few lines of code. The three big concepts that Express works with are:</p><ol><li>Routing</li><li>Middleware</li><li>Request/Response</li></ol><h4>Routing</h4><p>Routing aims to describe what code needs to be run in response to a request that the server received. This is typically done based on the combination of the URL pattern and the HTTP Method associated with the request.</p><p>For example, if a GET request is received for the URL /home, send back the HTML for the homepage. Or if a POST request is sent to /products, create a new product listing.</p><p>These are the basic building blocks of any API or web application, and Express provides us with flexible ways to define code to handle these requests.</p><p>Here’s a quick example of what routing looks like with Express:</p><pre>app.get(&quot;/test&quot;, function(req, res) {<br>  // run some code<br>  res.json({ ok: true });<br>});</pre><p>In this example, app is an instance of our Express server, app.get is the HTTP request method, and &quot;/test&quot; is a URL path we are defining for our server. The function passed in here is the handler that will run when a GET request is made to /test. The req and res parameters we&#39;ll cover next, but they stand for Request and Response respectively.</p><h4>Request/Response</h4><p>Often shortened to req and res, you&#39;ll see these everywhere when working with Express and other Node.js server frameworks. They represent the Request which was received by the server, and the Response which you will eventually send back.</p><p>These are based on objects that come built in to Node.js, the <a href="https://nodejs.org/api/http.html#http_class_http_clientrequest">ClientRequest</a> and <a href="https://nodejs.org/api/http.html#http_class_http_serverresponse">ServerResponse</a> objects — integral parts of an HTTP transaction.</p><p>A single HTTP transaction can be described by the Request and Response cycle.</p><ul><li>A client sends a request to the server.</li><li>The server receives the request and reads the data that accompanies it. This includes the headers, the URL path the request is being sent to, the HTTP method used to send the request, query parameters, cookies, the data or payload sent with the request (if any) — and more.</li><li>The server must send a response back to the client: this involves a status code, headers, content encoding, any data being returned, and again, many other possible things.</li><li>Once the server has sent the response back to the client, the HTTP transaction has completed.</li></ul><p>That is a <em>rough</em> explanation of what the Request/Response cycle looks like, but this interaction makes up the core of most HTTP transactions.</p><p>Express helps us complete these transactions by helpfully augmenting the built in Request and Response objects that the Node.js core http module provides when a request is received by your server.</p><p>Let’s take a look at the example from above one more time.</p><pre>app.get(&quot;/test&quot;, function(req, res) {<br>  // run some code<br>  res.json({ ok: true });<br>});</pre><p>In the handler function we are receiving two parameters, req and res. The req object will have all the information from the request we received. We can access properties on the req object to get data about the request like the URL path, the body of the request, headers, and more.</p><p>The res object represents the response we send back to the client. Express adds useful methods to res that help us send the response. Once the response is sent, the HTTP transaction has completed.</p><p>The example above is using res.json() to send a JSON response back to the client. That&#39;s one of the methods added by Express, and it will parse the object we pass into a JSON string and add it to the response body, set a Content-Type: application/json header on the response, and then send the response to the client.</p><p>Augmenting the req and res objects is a large part of how Express exposes and enhances functionality for your server, while still giving you control over how requests and responses are handled.</p><p>Check out the Express documentation to learn more about <a href="https://expressjs.com/en/api.html#req">the request object</a> as well as <a href="https://expressjs.com/en/api.html#res">the response object</a>.</p><h4>Middleware</h4><p>Middleware is code that executes somewhere during the life cyle of the request/response cycle, and is commonly used to add functionality or augment the behaviour of webserver. We [cover middleware in it’s own tutorial](./NEEDS LINK), but here is a general overview.</p><p>Middleware are functions that have access to the Request and Response objects. They can run any arbitrary code, and are executed one after another according to what order the middleware are stacked. Middleware are part of the program that add some kind of functionality to your application, often by augmenting or adding things to the req and res objects themselves. Middleware can be added into your application without needing to change much.</p><p>Express uses <a href="https://www.npmjs.com/package/connect">Connect style middleware</a> which is a common format for Node.js server frameworks. That means middleware written for Express can also be used in many other frameworks that implement Connect style middleware.</p><p>A common middleware used with Express is <a href="https://www.npmjs.com/package/cookie-parser">cookie-parser</a>. It parses the Cookie header of an incoming request and populates the cookie values on the req object under req.cookies as an object. This means that any other route handlers or middlewares that run after cookie-parser will have access to the cookies sent with the request.</p><p>Express itself is essentially just a collection of middlewares, plus routing capabilities. You can write your own middleware functions as well as use any of the countless middleware that are publicly available on the <a href="https://www.npmjs.com/">npmjs.com</a> package registry.</p><p>Middleware is one of the key ways that you add functionality to an Express server. It’s a flexible and powerful pattern that allows customization and additional logic to be introduced to the Request/Response cycle of your server.</p><h4>Community</h4><p>The final piece of what makes Express so powerful is the community of developers working with Express in production. It is one of the most popular server frameworks used with Node.js, and as a result there is a lot of knowledge and documentation that exists on the internet about it.</p><p>That is evident by the countless middlewares that exist to add functionality to an Express application. The Node.js ecosystem emphasizes using modules as building blocks, and Express takes full advantage of that.</p><p>Because of the large community, extensive documentation, and battle tested experience readily available on the internet, Express is a solid choice when building a web application with Node.js.</p><h4>Recap</h4><p>In this tutorial, we introduced the core concepts of the Express server framework. Express is a minimal and extensible framework that provides a set of common utilities for building servers and web applications. It’s built on top of Node.js’ built-in http module, but helps us accomplish the tasks of routing and handling the Request/Response cycle. Express uses middleware to extend its capabilities with code that we either write ourselves or that has been contributed by the large community using the project.</p><h4>Additional resources</h4><ul><li><a href="https://heynode.com/">Heynode.com</a>: Expert Node.js Training, anytime, anywhere</li><li><a href="https://expressjs.com/">Official Express.js Website</a> (expressjs.com)</li><li><a href="https://nodejs.org/api/http.html#http_http">Node.js </a><a href="https://nodejs.org/api/http.html#http_http">http Module Documentation</a> (nodejs.org)</li><li><a href="http://expressjs.com/en/guide/routing.html">Express Routing Guide</a> (expressjs.com)</li><li><a href="http://expressjs.com/en/guide/using-middleware.html">Express Using Middleware Guide</a> (expressjs.com)</li><li><a href="http://expressjs.com/en/guide/writing-middleware.html">Express Writing Middleware Guide</a> (expressjs.com)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f831d0c36a38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is an ETL (Extract, Transform, Load) Pipeline in Node.js?]]></title>
            <link>https://medium.com/@osiolabs/what-is-an-etl-extract-transform-load-pipeline-in-node-js-9a1a17de30f1?source=rss-1a9b50f5b873------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a1a17de30f1</guid>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[extract-transform-load]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[Osio Labs]]></dc:creator>
            <pubDate>Tue, 15 Oct 2019 15:06:29 GMT</pubDate>
            <atom:updated>2019-11-04T19:07:28.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_W0V6bQM68Bs1G3dnUujWg.png" /></figure><p>Node.js and ETL can be a powerful combination. Because it’s a non-blocking asynchronous language, you can query hundreds of database rows at once using Node.js without waiting for each query to complete before moving on to the next one.</p><p>ETL is a process of Extracting, Transforming, and Loading data from one or multiple sources into a destination. We can use this process to convert large amounts of data from one format to another. Whether you’re using Node.js or not, the parts of the pipeline entail the following:</p><ul><li><strong>Extract</strong> — Retrieve raw data from wherever it is, be that a database, an API, or any other source.</li><li><strong>Transform</strong> — Alter the data in some way. This could be restructuring the data, renaming keys in the data, removing invalid or unnecessary data points, computing new values, or any other type of data processing which converts what you have extracted into the format you need it to be.</li><li><strong>Load</strong> — Move the formatted data into its final destination (such as a database, flat file, or other structure) where it can be accessed by others.</li></ul><p><strong>Watch the entire free video on ETL Pipelines at </strong><a href="https://heynode.com/tutorial/what-etl-extract-transform-load-pipeline"><strong>HeyNode.com</strong></a><strong>.</strong></p><h3>Pipeline: a set of processes that allows data to flow.</h3><p>ETL aims to solve the problem of having data in disparate places and formats by allowing you to pull data from various sources into a centralized location with a standardized format. It’s called a “pipeline” because it’s a set of processes that allows data to flow from one destination to another, while passing through the three different stages.</p><p>You might implement a Node.js ETL pipeline when you want to periodically move stored data to a new database or destination in a different format than it’s stored in the data source.</p><p>Imagine you’re a retail company with stores around the world that transact in different local currencies. Every store reports its revenue to the head office at the end of the month.</p><p>Because the stores report revenue in different currencies, it would be difficult to analyze all the stores’ performance in direct relation to each other.</p><p>To better analyze the revenue from each store you can use an ETL process to standardize each report so they all use the same currency.</p><p>You would extract the data from the reports sent by the stores, transform the currency amounts from their local currency to a single base currency, and then load the modified report data to a final reporting database or other location.</p><p>This is just one example of using ETL to transform data from a data source into a new structure, but ETL has many uses.</p><p>What all ETL processes have in common is that they take data from one or more locations, modify and standardize it, and then load the data to another destination to be used in its new form.</p><h3>The Extract, Transform, Load process</h3><p>An ETL process is broken into three distinct steps, and each step plays an important role in the overall process.</p><p>First you’ll retrieve the data from the data source. This is your opportunity to select the data you want to use as input for the pipeline, and the place where Node.js can help improve your workflow with its asynchronous nature. The raw data you start with affects the output you’ll produce.</p><p>Each data source you extract from will require its own unique way to query or retrieve the data you’re interested in. Interacting with the data source and getting the right data is the main focus of the extract step, and frees up the other parts of the pipeline from having to worry about how to retrieve the data.</p><p>The transform step can be as simple or complex as your needs require. Here we focus on the data flowing through the pipeline, converting the raw data from the extract step into the data structures or values that you desire. This is done with functions that operate on the data, taking the raw data as input and outputting new records in your desired format. Your transform step can be looked at as taking input and returning an appropriate output based on the data it received.</p><p>Finally, loading the data is similar to the extract step, but instead of retrieving data, we are sending it somewhere. Whether the destination is a database, a data warehouse, or a flat file, we are interacting with a destination to deliver the data into where it can be used.</p><p>Breaking an ETL pipeline up into these smaller parts helps us think through the process from start to finish.</p><p>Moving through each step with a clear goal in mind (extract the data, modify the data, and load the data) takes a complex process and allows us to look at each step individually. You’ll also likely find parts of each step which are reusable, allowing you to find patterns within your process and take a more modular approach to moving data around.</p><p><strong>For more on ETL use cases, the limitations of Node.js, and to watch the full video tutorial, check out </strong><a href="https://heynode.com/tutorial/what-etl-extract-transform-load-pipeline"><strong><em>What Is an ETL (Extract, Transform, Load) Pipeline?</em></strong></a></p><p><strong>Check out our entire series on Data Brokering at </strong><a href="https://heynode.com/"><strong>HeyNode.com</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a1a17de30f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Module.exports to Keep Node.js Code Organized]]></title>
            <link>https://medium.com/@osiolabs/use-module-exports-to-keep-node-js-code-organized-9379526ebac8?source=rss-1a9b50f5b873------2</link>
            <guid isPermaLink="false">https://medium.com/p/9379526ebac8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Osio Labs]]></dc:creator>
            <pubDate>Tue, 18 Dec 2018 16:01:00 GMT</pubDate>
            <atom:updated>2020-01-14T21:33:02.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jm0ZB-xraNxgnBPLSz1Iyg.jpeg" /><figcaption>Photo by frank mckenna on Unsplash</figcaption></figure><p>Node doesn’t care if we write our entire project in one huge <em>index.js</em> file. But if you want people to be able to read your code, you need to organize it in a way that makes sense and is easy to maintain. Enter Node’s module system!</p><p>What exactly is a module? Modules organize related functions together into a file, that we can import later when we need to use them. A module encapsulates related code into a single unit, usually stored in a file. Every file in Node can be considered a module, and each has its own module global object available in the file that we will use to expose code for importing in another file.</p><p><strong>In this tutorial we’ll:</strong></p><ul><li>Learn about module.exports</li><li>Export helper functions from a file</li><li>Include our helper functions in another file using require</li></ul><p>By the end of this tutorial you should be able to use Node’s module system to create your own modules so you can reuse code in your project.</p><h4>Check out our full tutorial and video: <a href="https://heynode.com/tutorial/overview-nodes-module-system">An Overview of Node’s Module System</a>.</h4><h3>Goal</h3><p>Import helper functions from <em>helpers.js</em> in another file, <em>index.js</em>.</p><h3>What is module.exports?</h3><p>To export code from a file, we assign values to the file’s module.exports object. Each JavaScript file in Node has a module.exports object in its global scope that represents that specific file. That object will hold any code that we want to export from the file. We can assign an object, a single function, or any value to module.exports to be used again in another file.</p><p>This is part of the module system in Node. Each file has a global object in its scope called module , which holds information about that specific file. We can expose code from that file by assigning it to module.exports.</p><h3>What is require?</h3><p>Require helps us load modules. To import code from a file, we must pass the file’s path to require: require(‘./filepath’). Calling require on a JavaScript file will run the code in the file, and return the value of module.exports.</p><p>This is actually very similar to what happens when you require an npm module. Except in this instance, we are passing require a path to a file instead of the name of a package. When you require an npm package, the same thing is happening behind the scenes in your <em>node_modules/</em> folder, where the package is installed to.</p><p>Here we export a string from a file called <em>testModule.js</em>:</p><pre>// testModule.js<br>module.exports = &quot;This is a test!&quot;</pre><pre>// index.js<br>const test = require(&#39;./testModule.js&#39;)<br>console.log(test) // =&gt; &quot;This is a test!&quot;</pre><p>In any given file, we can assign things to module.exports to allow us to import them in another file using a require statement.</p><p>When the require is called with a file path, the code in that file will be evaluated and module.exports will be returned.</p><pre>// helpers.js<br>console.log(&#39;I got required!)<br>module.exports = &quot;Exported!&quot;</pre><pre>// index.js<br>const exportedValue = require(&#39;./helpers.js&#39;)</pre><p>The above code will output “I got required!” to the console, and exportedValue will be equal to `“Exported!” .</p><p>If we rerun the require statement (after the first instance), we would still get the exported value of module.exports, but the console.log would not run again. This is because require statements are cached; they are run once, and then calling them again will just return the value of module.exports.</p><p>You might also see ES6 code like this at some point:</p><pre>// helpers.js<br>export default = &quot;I&#39;m an export!&quot;</pre><pre>// index.js<br>import helpers from &#39;./helpers.js&#39;</pre><p>This uses ES6 module syntax, and currently no Node engine supports this by default. You can use this style if working with something like Babel that transpiles your code for you. But for now, know that we are talking about the CommonJS syntax of exports, module.exports.</p><h3>Creating a Helpers File</h3><p>So let’s use module.exports to export some functions from a <em>helpers.js</em> file to do some simple math, and then use them in another file, <em>index.js</em>, with the help of require.</p><p>One option is to export a single anonymous function from a file.</p><p><strong>Let’s export a single function that multiplies a number by 2 and use it in our <em>index.js</em> file:</strong></p><pre>// helpers.js<br>module.exports = function(x) {<br>  return x * 2<br>}</pre><pre>// index.js<br>const helpers = require(&#39;./helpers.js&#39;)<br>helpers(4) // =&gt; 8</pre><p>We set the value of module.exports to the function we want to import, and require it in <em>index.js</em>.</p><p>Handy, but what if you want to export several functions at once? Well, we can export an object literal that holds several functions, then access the functions by their names. This is also called Named Exports, because we can choose to later import only the properties we want by name.</p><pre>// helpers.js<br>module.exports = {<br>  multiplyByTwo: function(x) { return x *2 },<br>  divideByTwo: function(x) { return x / 2}<br>}</pre><pre>// index.js<br>const helpers = require(&#39;./helpers.js&#39;)<br>helpers.multiplyByTwo(10) // =&gt; 5<br>// or, you can import just the named property you need<br>const divideByTwo = require(&#39;./helpers.js&#39;).divideByTwo<br>divideByTwo(18) // =&gt; 9</pre><p>Requiring the file returns the object we exported with module.exports. You can also import only the property you need, by using dot syntax after the require statement.</p><p>Instead of having to declare the functions all in one place, we can make use of a different syntax. Here, we directly export a named property on the module.exports object.</p><pre>// helpers.js<br>module.exports.multiplyByTwo = function(x) { return x * 2 }<br>module.exports.divideByTwo = function(x) { return x / 2 }<br>function nonExportedFunction(x) {<br>  return x * 3<br>}</pre><pre>// index.js<br>const helpers = require(&#39;./helpers.js/)<br>const divideByTwo = require(&#39;./helpers.js&#39;).divideByTwo</pre><p>In the code above, module.exports will look the same as the object we exported in the previous example. Both will be an object with two keys, multiplyByTwo and divideByTwo. The only difference is that we assigned them one at a time.</p><p><strong>Note:</strong> Make sure you don’t mix the above syntax with exporting an object directly. If you assign something to module.exports later in your file, it will overwrite anything you had already exported.</p><pre>// helpers.js<br>module.exports.multiplyByTwo = function(x) { return x * 2 }<br>module.exports.divideByTwo = function(x) { return x / 2 }<br>module.exports = &quot;I just overwrote all my exports! Don&#39;t mix these styles!&quot;</pre><h3>Passing arguments to a module</h3><p>We can have a little fun with our math helpers by using some currying. <a href="https://www.sitepoint.com/currying-in-functional-javascript/">Currying is a concept from functional programming</a>: you call a function with a variable and get another function back that has that variable baked in already. It’s a sort of configuration, if you will. That’s a simple way to put it, but it can be very powerful.</p><p>Let’s make our math functions center around a single number to do operations with. We can pass in that number when requiring the file, and get back functions that multiply, divide, or add with the number we initially passed to our curry function.</p><pre>// curryHelpers.js<br>module.exports = function(x) {<br>  return {<br>    multiply: function(y) { return y * x },<br>    divide: function(y) { return y / x },<br>    add: function(y) { return y + x }<br>  }<br>}</pre><pre>// index.js<br>const byTwo = require(&#39;./curryHelpers.js&#39;)(2)<br>const byTen = require(&#39;./curryHelpers.js&#39;)(10)</pre><pre>byTwo.multiply(5) // =&gt; 10<br>byTwo.divide(14) // =&gt; 7<br>byTwo.add(9) // =&gt; 11</pre><pre>byTen.multiply(5) // =&gt; 50</pre><p>This is an example of passing a variable into a file’s scope using require and module.exports. We passed the number 2 into the curryHelpers file’s scope by calling the function returned by require. The object of functions we exported are now configured to multiply, divide, and add any number passed to it by the initial number we passed in, 2. We did the same thing with the number 10, and got back an object of functions configured with the number 10.</p><h3>exports as shorthand for module.exports</h3><p>Finally, a shorthand for module.exports can be used. The exports object is globally available as well, and points to the same object as module.exports.</p><p>So the following code is equivalent:</p><pre>// assigning named exports<br>module.exports.pizza = true<br>exports.pizza = true</pre><pre>// exporting an object<br>module.exports = {}<br>exports = {}</pre><h3>Wrap-up</h3><p>Node is a very modular language, and you can take advantage of that yourself by using module.exports to help export and reuse code in your project. Using require, you can import that code in any other file in your project. The idea of importing modules is very common in Node and understanding module.exports will help you navigate that modular approach.</p><p>We hope you’re able to use some of these patterns in your code!</p><p>If you want to learn more about module.exports and how it works, you could learn about <a href="https://stackoverflow.com/questions/15406062/in-what-scope-are-module-variables-stored-in-node-js">module scope</a> and the <a href="https://blog.risingstack.com/node-js-at-scale-module-system-commonjs-require/">CommonJS</a> module system.</p><p>Written by <a href="https://medium.com/u/ca9d3f36c91d">Jon Church</a> and <a href="https://medium.com/u/56f33349687e">Joe Shindelar</a></p><p><em>Welcome to </em><a href="https://heynode.com/"><em>Hey Node</em></a><em>, the new Node.js training site from Osio Labs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9379526ebac8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read/Write JSON Files with Node.js]]></title>
            <link>https://medium.com/@osiolabs/read-write-json-files-with-node-js-92d03cc82824?source=rss-1a9b50f5b873------2</link>
            <guid isPermaLink="false">https://medium.com/p/92d03cc82824</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Osio Labs]]></dc:creator>
            <pubDate>Fri, 14 Dec 2018 20:07:43 GMT</pubDate>
            <atom:updated>2019-12-02T15:40:12.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acocF8rHAPymDCg6-g4HXQ.jpeg" /><figcaption>Photo by Patrick Tomasso on Unsplash</figcaption></figure><p><strong><em>This article is part of </em>our first tutorial series, <em>Data Brokering with Node.js</em> on </strong><a href="https://heynode.com/"><strong><em>Hey Node</em></strong></a><strong><em>, the Node.js training site from Osio Labs.</em></strong></p><p><a href="https://heynode.com/tutorial/readwrite-json-files-nodejs"><strong><em>View the video tutorial on Hey Node</em></strong></a><strong><em>.</em></strong></p><p>When you want to store data between server restarts with Node, <a href="https://developer.mozilla.org/en-US/docs/Glossary/JSON">JSON</a> files are a simple and convenient choice. Whether you are reading a config file or persisting data for your application, Node has some built in utilities that make it easy to read and write JSON files.</p><p>Using JSON files in your app can be a useful way to persist data. We will look at a few different methods for working with JSON files.</p><p><strong>In this tutorial we will:</strong></p><ul><li>Read JSON data from disk</li><li>Learn to use fs module to interact with the filesystem</li><li>Persist data to a JSON file</li><li>Use JSON.parse and JSON.stringify to convert data to and from JSON format</li></ul><p>By the end of this tutorial you should be able to work with JSON files using Node’s built-in fs module.</p><h3>Goal</h3><p>Say you have a <em>customer.json</em> file saved to disk that holds a record for a customer in your store.</p><p>As part of your store app, you want to access the customer’s address, and then update the order count after an order is placed.</p><p>In this tutorial, we are going to look at how to read and write to our <em>customer.json</em> file.</p><pre>// customer.json<br>{<br>  &quot;name&quot;: &quot;Mega Corp.&quot;,<br>  &quot;order_count&quot;: 83,<br>  &quot;address&quot;: &quot;Infinity Loop Drive&quot;,<br>}</pre><h3>Work with files with fs</h3><p>Accessing files in Node is done with the <a href="https://nodejs.org/api/fs.html">native module fs</a>, which gives you functions to watch, read, and write files along with many other tools to work with the filesystem. Because it’s a native module, we can require it in our code without installing it. Just call const fs = require(‘fs’).</p><p>The fs module gives us the option of synchronous or asynchronous versions of many of its functions. The synchronous versions block execution of other code until they are done accessing the filesystem, reading, or writing data. An async function will run without blocking other code. You can learn more about sync/async behavior <a href="https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/">here</a>.</p><p>This synchronous behavior can be useful in some places, like at startup when reading a config file before any other code is run, but becomes a big issue when used in a webserver where all incoming requests would be blocked while a synchronous file read is running. For this reason, you generally want to use the async versions of fs functions in your code. We will focus on async operations, but will also show the synchronous equivalent.</p><p>To read and write files asynchronously with fs we will use fs.readFile and fs.writeFile.</p><p>We also will use the global JSON helper to convert objects to JSON strings, and JSON strings to objects.</p><p><strong>Reading a JSON file</strong></p><p>The simplest way to read a JSON file is to require it. Passing require() with the path to a JSON file will synchronously read and parse the data into a JavaScript object.</p><pre>const config = require(&#39;./config.json&#39;)</pre><p>But reading JSON files with require has its downsides. The file will only be read once; requiring it again returns the cached data from the first time require was run. This is fine for loading static data on startup (like config data). But for reading a file that changes on disk, like our <em>customer.json </em>might, we need to manually read the file using the asynchronous fs.readFile.</p><p><strong>Reading a file with fs.readFile</strong></p><p>To access the customer’s address, we need to:</p><ul><li>read the JSON data from the file</li><li>parse the JSON string into a JavaScript object</li></ul><p>To load the data from <em>customer.json</em> file, we will use fs.readFile, passing it the path to our file, an optional encoding type, and a callback to receive the file data.</p><p>If the file is successfully read, the contents will be passed to the callback.</p><pre>const fs = require(&#39;fs&#39;)</pre><pre>fs.readFile(&#39;./customer.json&#39;, &#39;utf8&#39;, (err, jsonString) =&gt; {<br>    if (err) {<br>        console.log(&quot;File read failed:&quot;, err)<br>        return<br>    }<br>    console.log(&#39;File data:&#39;, jsonString) <br>})</pre><p>‘./customer.json’ is the relative path to the the file ‘utf8’ is an optional parameter for the encoding of the file we are reading, this can be left out<br>(err, jsonString) =&gt; {} is the callback function that runs after the file has been read.</p><p><strong>Now we have the contents of the file as a JSON string, but we need to turn the string into an object.</strong></p><p>Before we can use the data from the callback in our code, we must turn it into an object. JSON.parse takes JSON data as input and returns a new JavaScript object. Otherwise, we would just have a string of data with properties we can’t access.</p><p>JSON.parse can throw exception errors and crash our program if passed an invalid JSON string. To prevent crashing we wrap JSON.parse in a try catch statement to gracefully catch any errors.</p><p>This example shows reading and parsing a JSON file:</p><pre>const fs = require(&#39;fs&#39;)</pre><pre>fs.readFile(&#39;./customer.json&#39;, &#39;utf8&#39;, (err, jsonString) =&gt; {<br>    if (err) {<br>        console.log(&quot;Error reading file from disk:&quot;, err)<br>        return<br>    }<br>    try {<br>        const customer = JSON.parse(jsonString)<br>        console.log(&quot;Customer address is:&quot;, customer.address) // =&gt; &quot;Customer address is: Infinity Loop Drive&quot;</pre><pre>} catch(err) {<br>        console.log(&#39;Error parsing JSON string:&#39;, err)<br>    }<br>})</pre><p>Using the jsonString from reading <em>customer.json</em>, we create an object, and can access the address property. If JSON.parse throws an error, we handle it in the catch block.</p><p>Now we have an object representation of the data in our <em>customer.json</em> file!</p><p>We can also read the file synchronously using fs.readFileSync. Instead of taking a callback, readFileSync returns the file content after reading the file.</p><pre>try {<br>  const jsonString = fs.readFileSync(&#39;./customer.json&#39;)<br>  const customer = JSON.parse(jsonString)<br>} catch(err) {<br>  console.log(err)<br>  return<br>}</pre><pre>console.log(customer.address) // =&gt; &quot;Infinity Loop Drive&quot;</pre><p>We can use this knowledge to create a reusable helper function to read and parse a JSON file.</p><p>Here we create a function called jsonReader that will read and parse a JSON file for us. It takes the path to the file and a callback to receive the parsed object and any errors. It will catch any errors thrown by JSON.parse for us.</p><pre>const fs = require(&#39;fs&#39;)</pre><pre>function jsonReader(filePath, cb) {<br>    fs.readFile(filePath, (err, fileData) =&gt; {<br>        if (err) {<br>            return cb &amp;&amp; cb(err)<br>        }<br>        try {<br>            const object = JSON.parse(fileData)<br>            return cb &amp;&amp; cb(null, object)<br>        } catch(err) {<br>            return cb &amp;&amp; cb(err)<br>        }<br>    })<br>}</pre><pre>jsonReader(&#39;./customer.json&#39;, (err, customer) =&gt; {<br>    if (err) {<br>        console.log(err)<br>        return<br>    }<br>    console.log(customer.address) // =&gt; &quot;Infinity Loop Drive&quot;<br>})</pre><h3>Writing to a file with fs.writeFile</h3><p>Writing JSON to the filesystem is similar to reading it. We will use fs.writeFile to asynchronously write data to a <em>newCustomer.json</em> file.</p><p>First, to write data to a JSON file, we must create a JSON string of the data with JSON.stringify. This returns a JSON string representation of a JavaScript object, which can be written to a file. Similar to parsing data into an object when reading a file, we must turn our data into a string to be able to write it to a file.</p><p>So we create a customer object with our data below, and turn it into a string.</p><pre>const customer = {<br>    name: &quot;Newbie Corp.&quot;,<br>    order_count: 0,<br>    address: &quot;Po Box City&quot;,<br>}</pre><pre>const jsonString = JSON.stringify(customer)<br>console.log(jsonString) <br>    // =&gt; &quot;{&quot;name&quot;:&quot;Newbie Co.&quot;,&quot;address&quot;:&quot;Po Box City&quot;,&quot;order_count&quot;:0}&quot;</pre><p><strong>If you try to write an object to a file without stringifying it, your file will be empty and look like this:</strong></p><p>[object, object]</p><p>Once the data is stringified, we can use fs.writeFile to create a new customer file. We pass fs.writeFile the filepath, our customer data to write, and a callback that will be excecuted after the file is written. If the <em>newCustomer.json</em> file doesn’t already exist, it will be created; if it does exist, it will be overwritten!</p><p><strong>Here is an example of writing a JSON file with </strong><strong>fs.writeFile:</strong></p><pre>const fs = require(&#39;fs&#39;)</pre><pre>const customer = {<br>    name: &quot;Newbie Co.&quot;,<br>    order_count: 0,<br>    address: &quot;Po Box City&quot;,<br>}</pre><pre>const jsonString = JSON.stringify(customer)</pre><pre>fs.writeFile(&#39;./newCustomer.json&#39;, jsonString, err =&gt; {<br>    if (err) {<br>        console.log(&#39;Error writing file&#39;, err)<br>    } else {<br>        console.log(&#39;Successfully wrote file&#39;)<br>    }<br>})</pre><p>And that’s it! Once the callback runs, the file has been written to disk. Note: we are only passed an error object; the filedata we wrote isn’t passed to the callback.</p><p>We can also write a file synchronously in the same way using fs.writeFileSync:</p><pre>const jsonString = JSON.stringify(customer)</pre><pre>fs.writeFileSync(&#39;./newCustomer.json&#39;, jsonString)</pre><p>After your file is finished writing, it will look something like this:</p><pre>{&quot;name&quot;:&quot;Newbie Co.&quot;,&quot;address&quot;:&quot;Po Box City&quot;,&quot;order_count&quot;:0}</pre><p>Stringifying by default puts your data all on a single line. Optionally, you can make the output file human-readable by passing the number of spaces to indent by to JSON.stringify:</p><pre>const jsonString = JSON.stringify(customer, null, 2)</pre><p>Above, we told stringify to indent the data with 2 spaces.</p><p>Now your output file should look like this:</p><pre>{<br>  &quot;name&quot;: &quot;Newbie Co.&quot;,<br>  &quot;address&quot;: &quot;Po Box City&quot;,<br>  &quot;order_count&quot;: 0<br>}</pre><p><strong>Updating JSON files</strong></p><p>Now that we are able to read and write our customer files, we can use them as a simple kind of database. If we want to update the data in the JSON file, we can read the contents, change the data, and then write the new data back to the file:</p><pre>jsonReader(&#39;./customer.json&#39;, (err, customer) =&gt; {<br>    if (err) {<br>        console.log(&#39;Error reading file:&#39;,err)<br>        return<br>    }</pre><pre>// increase customer order count by 1<br>    customer.order_count += 1</pre><pre>fs.writeFile(&#39;./customer.json&#39;, JSON.stringify(customer), (err) =&gt; {<br>        if (err) console.log(&#39;Error writing file:&#39;, err)<br>    })<br>})</pre><p>Definitely not the most efficient database you could choose, but working with JSON files like this is a simple way to persist data in your project.</p><p><strong>Wrapping up</strong></p><p>JSON is one of the most common types of data you’ll work with in Node, and being able to read and write JSON files is very useful. You’ve learned how to use fs.readFile and fs.writeFile to asynchronously work with the filesystem, as well as how to parse data to and from JSON format, and catch errors from JSON.parse.</p><p>You can use require to read a JSON file at startup to synchronously parse a JSON file in one line. And now you can use a simple JSON file as a data store.</p><p>If you want to learn more, you can read up on what <a href="https://developer.mozilla.org/en-US/docs/Glossary/JSON">JSON actually is</a>, and find out more about <a href="https://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node">synchronous vs asynchronous</a> code.</p><p>Written by <a href="https://medium.com/u/ca9d3f36c91d">Jon Church</a> and <a href="https://medium.com/u/56f33349687e">Joe Shindelar</a></p><p><em>Welcome to </em><a href="https://heynode.com/"><em>Hey Node</em></a><em>, the new Node.js training site from Osio Labs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92d03cc82824" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>