{"componentChunkName":"component---node-modules-nehalist-gatsby-theme-nehalem-src-templates-post-tsx","path":"/nodejs-file-io-using-callbacks","result":{"data":{"post":{"id":"745aa689-ebf0-5f72-8f96-3dec3cf511d2","headings":[{"depth":2},{"depth":2},{"depth":3},{"depth":3},{"depth":3},{"depth":2},{"depth":3},{"depth":4},{"depth":2},{"depth":3},{"depth":3}],"frontmatter":{"title":"Callback Functions: Simple Nodejs File IO","path":"/nodejs-file-io-using-callbacks","tags":["NodeJS"],"excerpt":"How to use Callback Functions to handle asynchronous tasks such as reading and writing files in Nodejs.","created":"2019-10-19T00:00:00.000Z","createdPretty":"19 October, 2019","updated":"2019-10-19T00:00:00.000Z","updatedPretty":"19 October, 2019","featuredImage":{"childImageSharp":{"sizes":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAMABQDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAAIDBP/EABYBAQEBAAAAAAAAAAAAAAAAAAIAAf/aAAwDAQACEAMQAAABkq4XmsoK/8QAGRABAAMBAQAAAAAAAAAAAAAAAQACEhED/9oACAEBAAEFAt8j6WjdmBLHL4J//8QAFBEBAAAAAAAAAAAAAAAAAAAAEP/aAAgBAwEBPwE//8QAFREBAQAAAAAAAAAAAAAAAAAAEBL/2gAIAQIBAT8Bo//EABgQAAIDAAAAAAAAAAAAAAAAAAAQETFB/9oACAEBAAY/AilpC//EABsQAAMAAwEBAAAAAAAAAAAAAAABESFBcTFR/9oACAEBAAE/IcF+KnoWHSrYoVTjMdblLbZ//9oADAMBAAIAAwAAABCLz//EABURAQEAAAAAAAAAAAAAAAAAABAR/9oACAEDAQE/EIf/xAAYEQACAwAAAAAAAAAAAAAAAAAAASExUf/aAAgBAgEBPxBtaJ0//8QAGxABAAIDAQEAAAAAAAAAAAAAAQARITFhkeH/2gAIAQEAAT8QNYpoTECPS/M0yeUYipmL6ewnp4wsc5tek//Z","aspectRatio":1.6129032258064515,"src":"/static/8f2afe03460156f93ec3da8886e76b96/f2cbb/cover.jpg","srcSet":"/static/8f2afe03460156f93ec3da8886e76b96/8850c/cover.jpg 200w,\n/static/8f2afe03460156f93ec3da8886e76b96/da113/cover.jpg 400w,\n/static/8f2afe03460156f93ec3da8886e76b96/f2cbb/cover.jpg 800w,\n/static/8f2afe03460156f93ec3da8886e76b96/c26c2/cover.jpg 1200w,\n/static/8f2afe03460156f93ec3da8886e76b96/9352a/cover.jpg 1600w,\n/static/8f2afe03460156f93ec3da8886e76b96/4fb49/cover.jpg 1920w","sizes":"(max-width: 800px) 100vw, 800px"}}}},"html":"<h2 id=\"overview\" style=\"position:relative;\"><a href=\"#overview\" aria-label=\"overview permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Overview</h2>\n<p>Hi guys! Today, I will be walking you through how to use Callback functions with Asynchronous tasks in Nodejs. The main goal of this tutorial will be to familiarize yourself with reading files in Nodejs while utilizing callback functions. I will be adding more posts in the future, on how to do the same thing with Promises and ES6 Async/Await. However, if you are just starting out callbacks is a great place to start! So, let's get started!</p>\n<h2 id=\"setup\" style=\"position:relative;\"><a href=\"#setup\" aria-label=\"setup permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Setup</h2>\n<h3 id=\"getting-the-files\" style=\"position:relative;\"><a href=\"#getting-the-files\" aria-label=\"getting the files permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Getting the files</h3>\n<p>A quick note: Before you can follow the steps of this tutorial you will need to have Nodejs installed on your system as well as Git.</p>\n<p>To get started, run this command to git clone the repo:</p>\n<div class=\"gatsby-highlight\" data-language=\"bash\"><pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token comment\"># using https</span>\n<span class=\"token function\">git</span> clone --branch Starting-Point-v2 https://github.com/andrewgeorgemitchell/amwebdev-nodejs-file-io-tut.git\n \n<span class=\"token comment\"># using ssh</span>\n<span class=\"token function\">git</span> clone --branch Starting-Point-v2 git@github.com:andrewgeorgemitchell/amwebdev-nodejs-file-io-tut.git</code></pre></div>\n<p><em>If your are curious what the --branch Starting-Point-v2 does, it clones the repo at a tag I setup to allow you to follow along in the tutorial from the beginning. If you wish to just see the finished repo simply remove --branch Starting-Point-v2 from the command. Also, if you’ve already cloned the repo, run git checkout master and you will be checked out to the latest commit.</em></p>\n<p>From here, you can open the folder in your favorite code editor aka <strong>VS Code</strong>.</p>\n<h3 id=\"the-file-structure\" style=\"position:relative;\"><a href=\"#the-file-structure\" aria-label=\"the file structure permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The File Structure</h3>\n<div class=\"gatsby-highlight\" data-language=\"jsx\"><pre class=\"language-jsx\"><code class=\"language-jsx\"><span class=\"token operator\">-</span> amwebdev<span class=\"token operator\">-</span>nodejs<span class=\"token operator\">-</span>file<span class=\"token operator\">-</span>io<span class=\"token operator\">-</span>tut<span class=\"token operator\">/</span>\n  <span class=\"token operator\">-</span> index<span class=\"token punctuation\">.</span>js <span class=\"token comment\">// our entry point file where we will right our program</span>\n  <span class=\"token operator\">-</span> data<span class=\"token operator\">/</span> <span class=\"token comment\">// folder where will read and write our data</span>\n    <span class=\"token operator\">-</span> users<span class=\"token punctuation\">.</span>csv <span class=\"token comment\">// a csv file I made to for data to read from</span>\n  <span class=\"token operator\">-</span> <span class=\"token keyword\">package</span><span class=\"token punctuation\">.</span>json <span class=\"token comment\">// npm package.json (not used in this tutorial)</span></code></pre></div>\n<h3 id=\"nodejs-modules\" style=\"position:relative;\"><a href=\"#nodejs-modules\" aria-label=\"nodejs modules permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Nodejs Modules</h3>\n<p>In Nodejs most of the core functionality has been segmented out into modules, for example in this tutorial we will be using the 'fs' module for reading and writing to the filesystem. Importing the fs module is simple just <strong>add the following to the top of index.js</strong>:</p>\n<div class=\"gatsby-highlight\" data-language=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> fs <span class=\"token operator\">=</span> <span class=\"token function\">require</span><span class=\"token punctuation\">(</span><span class=\"token string\">'fs'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p><em>Note: You don't have to run npm install fs because fs is included by default inside your installation of Nodejs. However for non-core Nodejs packages you will have to install them using npm.</em></p>\n<h2 id=\"how-to-readwrite-files-in-3-different-methods\" style=\"position:relative;\"><a href=\"#how-to-readwrite-files-in-3-different-methods\" aria-label=\"how to readwrite files in 3 different methods permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How to Read/Write files in 3 Different Methods</h2>\n<p>When reading and writing from files in Nodejs, you are performing what is called an asynchronous action, meaning an action that has no scheduled or predictable end time. Nodejs has 3 different syntactical ways of dealing with asynchronous action and while some are definitely better than others (cough cough async/await) all of them are worth understanding, because the likelihood you come across all three is very high. So we will go over all of them in order of difficulty (for beginners) as well as the order that most people should learn them in.</p>\n<p><strong>The three methods are:</strong></p>\n<ul>\n<li><a href=\"#callback-method\">Callback Method</a></li>\n<li>Promise Method (Coming Soon)</li>\n<li>Async/Await Method (Coming Soon)</li>\n</ul>\n<h3 id=\"callback-method\" style=\"position:relative;\"><a href=\"#callback-method\" aria-label=\"callback method permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Callback Method</h3>\n<p>Simply put, callbacks are a function which you pass into an asynchronous function  that will be executed once the asynchronous function finishes. So in layman terms it works like this:</p>\n<div class=\"gatsby-highlight\" data-language=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// Asynchronous Function: Do some asynchronous action such as read from file</span>\n  <span class=\"token comment\">// Callback Function: Once your done do something with the file</span></code></pre></div>\n<p>The strange thing about this is that we don't know when the second line or callback function will execute. It could be in a minute, or in an hour. So in order to avoid errors, we have to make sure our callback function doesn't rely on anything but what is getting passed to it from the original asynchronous function.</p>\n<p>As a final note, dealing with errors in callbacks can be somewhat repetitive, but it needs to be done, so we will employ what is called error first callbacks which deal with the error case first, then deals with the success case.</p>\n<p>So let’s adjust the pseudo code to handle errors:</p>\n<div class=\"gatsby-highlight\" data-language=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// Asynchronous Function: Do some asynchronous action</span>\n  <span class=\"token comment\">// Callback Function: Once said action is done</span>\n    <span class=\"token comment\">// If there is an error deal with it</span>\n    <span class=\"token comment\">// If there isn't an error do what I wanted</span></code></pre></div>\n<h4 id=\"reading-from-file\" style=\"position:relative;\"><a href=\"#reading-from-file\" aria-label=\"reading from file permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Reading from file</h4>\n<p>When it comes to implementing a function to read a file from the filesystem we will take advantage of nodes built in fs (filesystem) module to do this. Specifically we will be using the <a href=\"https://nodejs.org/api/fs.html\">fs.readFile</a> method which takes two arguments:</p>\n<ul>\n<li>the path to the file you want to read</li>\n<li>the callback function to execute once it has the files data</li>\n</ul>\n<p>So let’s take the pseudo code from above and add some Nodejs skeleton to it.</p>\n<div class=\"gatsby-highlight\" data-language=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// Callback Function: Do something with the file once its read</span>\n<span class=\"token keyword\">const</span> <span class=\"token function-variable function\">readFileCallbackFunction</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token parameter\">error<span class=\"token punctuation\">,</span> file</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// If there is an error deal with it</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">throw</span> error<span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token comment\">// If there isn't an error do what I wanted with the file</span>\n<span class=\"token punctuation\">}</span>\n \n<span class=\"token comment\">// Asynchronous Function: Read file</span>\nfs<span class=\"token punctuation\">.</span><span class=\"token function\">readFile</span><span class=\"token punctuation\">(</span>filepath<span class=\"token punctuation\">,</span> readFileCallbackFunction<span class=\"token punctuation\">)</span></code></pre></div>\n<p>So above you can see we actually moved the callback function above the fs.readFile which seems counterintuitive but we are actually just declaring the callback function so it can be <strong>passed down into</strong> fs.readFile(). This method is actually somewhat unorthodox as normally what is very common for callback functions is not give it a name at all, but instead to just declare it as an anonymous function when you need it like this:</p>\n<div class=\"gatsby-highlight\" data-language=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// Asynchronous Function: Read file</span>\nfs<span class=\"token punctuation\">.</span><span class=\"token function\">readFile</span><span class=\"token punctuation\">(</span>filepath<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span><span class=\"token parameter\">error<span class=\"token punctuation\">,</span> file</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// If there is an error deal with it</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">throw</span> error<span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token comment\">// If there isn't an error do what I wanted</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p>Great! Now we are using an anonymous function, which is definitely the more popular approach when using callbacks. That being said, this can definitely be more confusing for beginners, so if you wish to use the first method feel free, but I will be using the second as it is more of an industry standard.</p>\n<p>Now we actually have a working function that will read the file’s contents, but we need to do something with the raw file data that was passed into our callback by fs.readFile. Spoiler alert, fs.readFile gives the raw buffer data which isn't very useful to anyone, so let’s look into how to change into a string. So let’s use the very helpful .toString method available on any variable that is of type buffer.</p>\n<p>To do this we need only add one line, but let’s also add the code to actually read the file of our choosing because filepath is not defined yet: </p>\n<div class=\"gatsby-highlight\" data-language=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> filepath <span class=\"token operator\">=</span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span>__dirname<span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token string\">/data/users.csv</span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">;</span>\n \n<span class=\"token comment\">// Asynchronous Function: Read file</span>\nfs<span class=\"token punctuation\">.</span><span class=\"token function\">readFile</span><span class=\"token punctuation\">(</span>filepath<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span><span class=\"token parameter\">error<span class=\"token punctuation\">,</span> file</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// If there is an error deal with it</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">throw</span> error<span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token comment\">// If there isn't an error do what I wanted</span>\n  <span class=\"token keyword\">const</span> fileStringData <span class=\"token operator\">=</span> file<span class=\"token punctuation\">.</span><span class=\"token function\">toString</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  console<span class=\"token punctuation\">.</span><span class=\"token function\">log</span><span class=\"token punctuation\">(</span>fileStringData<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p>Now if we run our program using this command:</p>\n<div class=\"gatsby-highlight\" data-language=\"bash\"><pre class=\"language-bash\"><code class=\"language-bash\">node index.js</code></pre></div>\n<p>We will get this output to the console.</p>\n<div class=\"gatsby-highlight\" data-language=\"bash\"><pre class=\"language-bash\"><code class=\"language-bash\">name, age, favAnimal\nEli Miller, <span class=\"token number\">24</span>, Dog\nJohn Smith, <span class=\"token number\">35</span>, Tiger\nBetsy Blue, <span class=\"token number\">19</span>, Warthog\nJustin Long, <span class=\"token number\">15</span>, Cat</code></pre></div>\n<p>This isn't very useful though so let’s convert this CSV string into a javascript array of user objects where the first row is used as the keys and the rows after that are the values. To keep our code clean, let’s create a helper function to do this called convert csvToObject.</p>\n<div class=\"gatsby-highlight\" data-language=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token keyword\">const</span> <span class=\"token function-variable function\">csvToObject</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token parameter\">csvString</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> splitByLineEndingAndCommas <span class=\"token operator\">=</span> csvString\n    <span class=\"token punctuation\">.</span><span class=\"token function\">split</span><span class=\"token punctuation\">(</span><span class=\"token string\">'\\n'</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// splits the string by new line so we end of with an array where each line is now on its own</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">map</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">lineString</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> lineString<span class=\"token punctuation\">.</span><span class=\"token function\">split</span><span class=\"token punctuation\">(</span><span class=\"token string\">','</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">// Split each line by , so that each value is on its own</span>\n \n  <span class=\"token comment\">// We end up with this:</span>\n  <span class=\"token comment\">// [</span>\n  <span class=\"token comment\">//   [ 'name', ' age', ' favAnimal' ],</span>\n  <span class=\"token comment\">//   [ 'Eli Miller', ' 24', ' Dog' ],</span>\n  <span class=\"token comment\">//   [ 'John Smith', ' 35', ' Tiger' ],</span>\n  <span class=\"token comment\">//   [ 'Betsy Blue', ' 19', ' Warthog' ],</span>\n  <span class=\"token comment\">//   [ 'Justin Long', ' 15', ' Cat' ]</span>\n  <span class=\"token comment\">// ]</span>\n \n  <span class=\"token comment\">// Create a header row for reference</span>\n  <span class=\"token keyword\">const</span> headerRow <span class=\"token operator\">=</span> splitByLineEndingAndCommas<span class=\"token punctuation\">[</span><span class=\"token number\">0</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">;</span>\n  <span class=\"token comment\">// Create our array of user objects</span>\n  <span class=\"token keyword\">const</span> users <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">;</span>\n  <span class=\"token comment\">// Loop over the lines skipping the first header row because it doesn't represent a user</span>\n  <span class=\"token keyword\">for</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">let</span> i <span class=\"token operator\">=</span> <span class=\"token number\">1</span><span class=\"token punctuation\">;</span> i <span class=\"token operator\">&lt;</span> splitByLineEndingAndCommas<span class=\"token punctuation\">.</span>length<span class=\"token punctuation\">;</span> i <span class=\"token operator\">+=</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Create the blank object for the current user</span>\n    <span class=\"token keyword\">const</span> newUser <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n    <span class=\"token comment\">// Create a reference variable to the current line array</span>\n    <span class=\"token keyword\">const</span> line <span class=\"token operator\">=</span> splitByLineEndingAndCommas<span class=\"token punctuation\">[</span>i<span class=\"token punctuation\">]</span><span class=\"token punctuation\">;</span>\n    <span class=\"token comment\">// Loop over the headers row</span>\n    <span class=\"token keyword\">for</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">let</span> b <span class=\"token operator\">=</span> <span class=\"token number\">0</span><span class=\"token punctuation\">;</span> b <span class=\"token operator\">&lt;</span> headerRow<span class=\"token punctuation\">.</span>length<span class=\"token punctuation\">;</span> b<span class=\"token operator\">++</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token keyword\">const</span> headerKey <span class=\"token operator\">=</span> headerRow<span class=\"token punctuation\">[</span>b<span class=\"token punctuation\">]</span><span class=\"token punctuation\">;</span>\n      <span class=\"token comment\">// Assign the key value pair for each header</span>\n      newUser<span class=\"token punctuation\">[</span>headerKey<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> line<span class=\"token punctuation\">[</span>b<span class=\"token punctuation\">]</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n    <span class=\"token comment\">// Push the finished user to the users array</span>\n    users<span class=\"token punctuation\">.</span><span class=\"token function\">push</span><span class=\"token punctuation\">(</span>newUser<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span>\n \n  <span class=\"token keyword\">return</span> users<span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Which results in very clean data like this:</p>\n<div class=\"gatsby-highlight\" data-language=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\">users<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span>\n  <span class=\"token punctuation\">{</span> name<span class=\"token operator\">:</span> <span class=\"token string\">'Eli Miller'</span><span class=\"token punctuation\">,</span> age<span class=\"token operator\">:</span> <span class=\"token string\">'24'</span><span class=\"token punctuation\">,</span> favAnimal<span class=\"token operator\">:</span> <span class=\"token string\">'Dog'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">{</span> name<span class=\"token operator\">:</span> <span class=\"token string\">'John Smith'</span><span class=\"token punctuation\">,</span> age<span class=\"token operator\">:</span> <span class=\"token string\">'35'</span><span class=\"token punctuation\">,</span> favAnimal<span class=\"token operator\">:</span> <span class=\"token string\">'Tiger'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">{</span> name<span class=\"token operator\">:</span> <span class=\"token string\">'Betsy Blue'</span><span class=\"token punctuation\">,</span> age<span class=\"token operator\">:</span> <span class=\"token string\">'19'</span><span class=\"token punctuation\">,</span> favAnimal<span class=\"token operator\">:</span> <span class=\"token string\">'Warthog'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">{</span> name<span class=\"token operator\">:</span> <span class=\"token string\">'Justin Long'</span><span class=\"token punctuation\">,</span> age<span class=\"token operator\">:</span> <span class=\"token string\">'15'</span><span class=\"token punctuation\">,</span> favAnimal<span class=\"token operator\">:</span> <span class=\"token string\">'Cat'</span> <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">]</span></code></pre></div>\n<p>Perfect! Now we have our array of users that we could do all types of things with.</p>\n<div class=\"gatsby-highlight\" data-language=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// Asynchronous Function: Read file</span>\nfs<span class=\"token punctuation\">.</span><span class=\"token function\">readFile</span><span class=\"token punctuation\">(</span>filepath<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span><span class=\"token parameter\">error<span class=\"token punctuation\">,</span> file</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// If there is an error deal with it</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">throw</span> error<span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token comment\">// If there isn't an error do what I wanted</span>\n  <span class=\"token keyword\">const</span> fileStringData <span class=\"token operator\">=</span> file<span class=\"token punctuation\">.</span><span class=\"token function\">toString</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token keyword\">const</span> users <span class=\"token operator\">=</span> <span class=\"token function\">csvToObject</span><span class=\"token punctuation\">(</span>fileStringData<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token comment\">// Do something with users</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<h2 id=\"wrapping-up\" style=\"position:relative;\"><a href=\"#wrapping-up\" aria-label=\"wrapping up permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Wrapping Up</h2>\n<p>Callbacks and asynchronous functions can be complicated when you first start, but like most programming principles, if you keep practicing you will get the hang of them. In the future I will be adding guides for both Promises and Async/Await, so if callbacks and their messy looking coding style left you feeling icky then you should stay tuned. Callbacks are a thing of the past and Promises and Async/Await are the future.</p>\n<h3 id=\"part-2-simple-nodejs-file-io-with-promises-coming-soon\" style=\"position:relative;\"><a href=\"#part-2-simple-nodejs-file-io-with-promises-coming-soon\" aria-label=\"part 2 simple nodejs file io with promises coming soon permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Part 2: Simple Nodejs File IO With Promises (Coming Soon)</h3>\n<h3 id=\"part-3-simple-nodejs-file-io-with-asyncawait-coming-soon\" style=\"position:relative;\"><a href=\"#part-3-simple-nodejs-file-io-with-asyncawait-coming-soon\" aria-label=\"part 3 simple nodejs file io with asyncawait coming soon permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Part 3: Simple Nodejs File IO With Async/Await (Coming Soon)</h3>"},"primaryTag":{"name":"NodeJS","color":"#3C873A"}},"pageContext":{"postId":"745aa689-ebf0-5f72-8f96-3dec3cf511d2","primaryTag":"NodeJS"}},"staticQueryHashes":["1116962356","2041457101","2275848304","2775657032","545095672"]}