<?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 Cameron Nokes on Medium]]></title>
        <description><![CDATA[Stories by Cameron Nokes on Medium]]></description>
        <link>https://medium.com/@ccnokes?source=rss-718683c9a8c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R1sVOkLuy9wy-sZ51fQypg.jpeg</url>
            <title>Stories by Cameron Nokes on Medium</title>
            <link>https://medium.com/@ccnokes?source=rss-718683c9a8c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:02:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ccnokes/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 convert HEIC image files to JPG in bash on macOS]]></title>
            <link>https://medium.com/macoclock/how-to-convert-heic-image-files-to-jpg-in-bash-on-macos-3fd6b08bcdfe?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fd6b08bcdfe</guid>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Sun, 28 Jun 2020 00:00:00 GMT</pubDate>
            <atom:updated>2020-07-01T04:58:05.893Z</atom:updated>
            <content:encoded><![CDATA[<h4>We’ll create a script that uses imagemagick to bulk convert HEIC files</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*dYLWe1OyafyAxvJw.jpg" /><figcaption><em>On the surface, using imagemagick might not seem as exciting as creating a potion, but it is actually pretty thrilling.</em></figcaption></figure><blockquote><em>Originally published at </em><a href="https://cameronnokes.com/blog/how-to-convert-heic-image-files-to-jpg-in-bash-on-macos/"><em>https://cameronnokes.com</em></a><em> on June 28, 2020.</em></blockquote><p>Apple iPhones store images in HEIC format (high efficiency image compression). HEIC has more advanced compression that JPG, which is great, the problem is that most other devices or websites can’t use an HEIC file. Want to upload an iPhone photo to a website? You’ll probably need to convert it first if you’re on a desktop. Sure, there are ways to make it so that iOS stores your photos as JPG but then your photos take up more disk space.</p><p>Awhile ago, I created a bash script to automate the conversion process for me. For the script to work, you’ll need to have <a href="https://imagemagick.org/index.php">imagemagick</a> installed. I recommend first installing <a href="https://brew.sh/">homebrew</a>, a macOS package manager, and then installing imagemagick through that.</p><h3>The script</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f376f31dfdbf649af1637172e2d0f27/href">https://medium.com/media/2f376f31dfdbf649af1637172e2d0f27/href</a></iframe><p>Here’s how it works:</p><ol><li>First, we set some bash settings to give us saner behavior in regards to errors. This is a great <a href="https://sipb.mit.edu/doc/safe-shell/">article on safe shell scripting</a> that delves into that more deeply.</li><li>We get a count of HEIC files in the directory it’s being run in and write that to count stdout. I like to do this to just verify that the script is running in the right place. We use find with a depth of 1 so that we don’t get do down subdirectories. This is then piped to wc -l which will return a count of the number of lines, effectively getting a count of files that&#39;ll be converted. From there we pipe to sed, because for reasons unknown to me, wc -l returns a number with several spaces in front of it, and the sed script just removes the whitespace.</li><li>We run the imagemagick command that converts HEIC to JPG.</li><li>We prompt the user if they also want to remove the HEIC files now that they’ve been converted. Whatever the user types and then hits enter will be stored to a variable named remove.</li><li>If the user typed y, then we used find to delete all the HEIC files.</li></ol><h3>Make it available everywhere</h3><p>There’s multiple ways to expose a bash script to your PATH so it can be run anywhere. The way I do it is in my home directory, I have a folder called scripts. I added that folder to my PATH like so in my .zprofile:</p><pre>export PATH=&quot;$PATH:$HOME/scripts&quot;</pre><p>I put the script above in that folder, gave it execute permissions ( chmod +x) and voilà -- I can run that script anywhere in my bash shell terminal.</p><p>Depending on your needs, you could add more options to that script to choose what file format to convert to (we did jpg but you could also do png, for example). You could also make it enter subdirectories. Lots of fun possibilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd6b08bcdfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/macoclock/how-to-convert-heic-image-files-to-jpg-in-bash-on-macos-3fd6b08bcdfe">How to convert HEIC image files to JPG in bash on macOS</a> was originally published in <a href="https://medium.com/macoclock">Mac O’Clock</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to know if a desktop app uses Electron]]></title>
            <link>https://medium.com/@ccnokes/how-to-know-if-a-desktop-app-uses-electron-59559e9ee580?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/59559e9ee580</guid>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-12-27T23:06:22.130Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*3TNNwVwaRisDYC6E.png" /></figure><blockquote>Originally published at <a href="https://cameronnokes.com/blog/how-to-know-if-a-desktop-app-uses-electron/">https://cameronnokes.com</a> on December 23, 2019.</blockquote><p><a href="https://electronjs.org/">Electron</a> is a popular platform to publish desktop apps these days. Many people are familiar with popular applications like VSCode or Slack that are written in Electron, but is there a way I can check on my own to know if an app was built using Electron?</p><p>Yes. In fact, I created a quick video of the process:</p><h3>Cameron Nokes on Twitter</h3><p>How to know if a desktop app uses #Electron https://t.co/5tAprex2BV</p><p>I was surprised at how many views it got (I know, it’s not that many in the grand scheme of things but I’m small-time so it was a lot for me).</p><p>Written out, the above process is this:</p><ol><li>Right click .app file</li><li>Click “Show Package Contents”</li><li>Navigate into Contents</li><li>Navigate into Frameworks</li><li>Check if there’s a Electron Framework.framework file</li></ol><h3>Why does this work?</h3><p>macOS apps are actually a directory that simply looks like a file. Application bundles follow a specific format. A “framework”, which is a dynamic shared library, will always reside in Contents/Frameworks. You can read more about macOS app bundles on <a href="https://en.wikipedia.org/wiki/Bundle_(macOS)#macOS_application_bundles">Wikipedia</a> or <a href="https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html#//apple_ref/doc/uid/10000123i-CH101-SW1">Apple&#39;s developer docs</a>.</p><p>That process might sound tedious if you want to check all of your applications at once. So, that’s why I created a bash script that checks for you 😎:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1974ac1842b49f86b961dfacb2a8a8ae/href">https://medium.com/media/1974ac1842b49f86b961dfacb2a8a8ae/href</a></iframe><p>The overall process of the script is that it runs a find for every .app directory. For each match, it checks if a Electron Framework.framework file exists. If it does, we found an app that uses Electron. Interestingly I found that the find runs really slow without the -maxdepth option (using -depth didn&#39;t help, had to be maxdepth). I&#39;m not exactly sure why, I&#39;ll have to dig into that later. My best guess is that some of the .app folders go really deep and -maxdepth limited the recursion in a way that -depth doesn&#39;t.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59559e9ee580" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sed: a 5 minute practical guide]]></title>
            <link>https://medium.com/@ccnokes/sed-a-5-minute-practical-guide-b04a8663173d?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b04a8663173d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Thu, 19 Dec 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-12-19T22:15:27.425Z</atom:updated>
            <content:encoded><![CDATA[<h4>While sed sometimes appears cryptic, once you understand the syntax, it’s easy</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/0*-hZ6PTU3RbsRxCnO.jpg" /></figure><p>Sed, which stands for stream editor, is probably most commonly used to find and replace strings in bash scripts. Something like this:</p><pre>sed &#39;s/foo/bar/g&#39; foo.txt</pre><p>It’s a powerful tool, but one that’s a little confusing. For me, at first glance sed looked about as confusing as regex was before I learned it — just a bunch of characters and symbols haphazardly mashed together. Sed is actually pretty straightforward once you know it’s simple syntax. Once learned, it enables you to do powerful things like programmatically substitute, delete, or insert text in a file or stream.</p><h3>How the command works</h3><p>The sed command itself is straightforward and follows this form:</p><pre>sed [options/flags...] [sed script] [input file(s)]</pre><p>Note that you’ll generally want to wrap what you pass to sed in single quotes. This prevents bash from interpreting the content and replacing special characters. Also, as we’ll see more of later, macOS sed and GNU/Linux sed are different. macOS sed is pretty old, so it’s not as capable. So only GNU sed can handle multiple input files or globs.</p><h3>How the syntax works</h3><p>Here’s how sed’s script syntax works:</p><pre>[address]command[options]</pre><ul><li>Address: can be a line number, range of line numbers, or a regex</li><li>Command: just one letter, like s, which stands for &quot;substitute&quot;</li><li>Options: depends on the command</li></ul><p>🤯I wish I had known that a lot sooner.</p><p>Note that sed is not big on spaces between each of those things. On macOS (BSD) sed, a space between the address and command is okay though.</p><p>Let’s see how that works with some examples.</p><h3>Substitute, s</h3><pre>sed &#39;s/target/replacement/g&#39; file.txt</pre><p>This will globally substitute the word target with replacement. No address is provided, so it applies globally.</p><p>The command is s, which stands for &quot;substitute&quot;. For the options, s takes a regex, which is /target/replacement/g. The g flag is the regex global flag. This ensures that every match is replaced.</p><p>So if we wanted to provide an address to constrain what lines the command applies to, we could do something like this:</p><pre>sed &#39;1,5 s/target/replacement/g&#39; file.txt</pre><p>Same as before but only lines 1 through 5 will be affected by the command.</p><p>A really common use of substitute is to delete something in a line, like so:</p><pre>sed &#39;s/remove//g&#39; file.txt</pre><p>This will remove all instances of the word “remove” by simply replacing it with nothing.</p><h3>Delete, d</h3><p>The delete command will remove an entire line. Let’s say we wanted to use a regex to determine which lines we want to delete. We pass that regex to the address, like so:</p><pre>sed &#39;/^[[:space:]]/ d&#39; file.txt</pre><p>This will delete ( d in sed) all lines that start with a space, newline, or tab. d doesn&#39;t have any options. (Note [[:space:]] is a <a href="https://www.tldp.org/LDP/abs/html/x17129.html">bash regex</a> character class thing. There are some differences between JavaScript regex and bash&#39;s regex.)</p><h3>Modify in place, -i</h3><p>If you’ve tried any of the above examples out, you may have noticed that they all output the modified text to stdout and leave the original source unmodified. If we wanted to preserve the original but create a new file from the modifications we could do that using plain bash redirection:</p><pre>sed &#39;/^[[:space:]]/ d&#39; file.txt &gt; file-modified.txt</pre><p>But what if we want to modify it in place?</p><pre>sed -i &#39;/^[[:space:]]/ d&#39; file.txt</pre><p>The -i flag, which stands for &quot;in-place&quot;, will do just that. But here&#39;s a caveat--while this works as is on Linux/GNU sed (which can be installed on macOS if you so desire), on default macOS sed, this fails. That&#39;s because you can pass an argument to the -i flag which is optional on newer versions of sed but required on older ones. That argument specifies the extension of a backup file.</p><pre>sed -i &#39;.bak&#39; &#39;/^[[:space:]]/ d&#39; file.txt</pre><p>This command creates file.txt.bak with the original source, and sets the modified text into file.txt. You can pass an empty string to -i to make it not create a backup. This is what I do on macOS&#39;s older sed when I want to edit in place without a backup.</p><pre>sed -i &#39;&#39; &#39;/^[[:space:]]/ d&#39; file.txt</pre><h3>Insert, i</h3><p>Let’s say I have a bunch of files that I want to insert a generic header on. Because GNU sed is newer and much easier than macOS’s, we’ll start with that one:</p><pre>sed -i &#39;1 i // Copyright 2019 Cameron Nokes&#39; *.js</pre><p>So we pass -i flag to sed with no arguments to tell it to modify in place. Then in our sed script, we want to insert on the first line, so the address is 1. Then i, for insert. Then the content we want inserted comes after. After the sed script, we pass a glob *.js to tell it modify all .js files in this directory. That&#39;s it, pretty easy.</p><p>On macOS, things are more involved and I personally struggled to do this just on the command line, so I created a script:</p><pre><strong>for</strong> file <strong>in</strong> $(ls *.js); <strong>do</strong><br>  sed -i &#39;&#39; &#39;1 i\<br>  // Copyright 2019 Cameron Nokes<br>  &#39; $file<br><strong>done</strong></pre><p>There’s a few important differences to point out here:</p><ol><li>macOS sed can’t operate on multiple files, so I loop through them</li><li>sed’s i command on macOS sed has to be followed by a \ and a newline</li></ol><p>Unfortunately the syntax gets a little awkward on macOS.</p><h3>Multiple commands</h3><p>You can do multiple sed commands in one script by separating them with a semicolon.</p><pre>sed &#39;1 d; 2,5 s/target/replacement/g&#39; file.txt</pre><p>This will delete the first line, then do a substitute on lines 2 through 5.</p><p>That’s it for sed. Sed can even do quite a bit more! You can read the full manual here <a href="https://www.gnu.org/software/sed/manual/sed.html">https://www.gnu.org/software/sed/manual/sed.html</a>.</p><p><em>Originally published at </em><a href="https://cameronnokes.com/blog/sed-5-min-practical-guide/"><em>https://cameronnokes.com</em></a><em> on December 19, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b04a8663173d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your own event emitter using only native DOM APIs]]></title>
            <link>https://medium.com/cameron-nokes/build-your-own-event-emitter-using-only-native-dom-apis-b064aa2df09e?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b064aa2df09e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[dom]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[web-platform]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Sat, 02 Nov 2019 20:53:44 GMT</pubDate>
            <atom:updated>2020-01-09T04:28:15.881Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using EventTarget and CustomEvent, we can create our own event emitter, no library needed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pVFRBP2WcSbvthtg.jpeg" /></figure><blockquote><em>Originally published at </em><a href="https://cameronnokes.com/blog/build-your-own-event-emitter-using-only-native-dom-apis/"><em>https://cameronnokes.com</em></a><em>.</em></blockquote><p>The Event emitter pattern (maybe better said as the <a href="https://en.wikipedia.org/wiki/Observer_pattern">observer pattern</a>) is a bedrock in the JavaScript ecosystem. It’s a well-known, useful pattern for decoupling concerns in an application. Many codebases I’ve worked on use a library such as <a href="https://github.com/primus/eventemitter3">eventemitter3</a> or <a href="https://github.com/developit/mitt">mitt</a>. But did you know that you can technically use built-in DOM APIs to get the same functionality, no library needed? 🤯</p><p>To accomplish this, we’ll use <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget">EventTarget</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent">CustomEvent</a>.</p><pre>let eventEmitter = new EventTarget(); eventEmitter.addEventListener(&#39;my-event&#39;, console.log); eventEmitter.dispatchEvent(<br>  new CustomEvent(&#39;my-event&#39;, { detail: 123 })<br>); <br>eventEmitter.removeEventListener(&#39;my-event&#39;, console.log);</pre><p>That’s it. I know, it’s a little verbose, but that can be changed. The API should probably be familiar to you, but let’s go over what everything does.</p><h3>EventTarget</h3><p>This is a core DOM API that other DOM classes like Element, Window, or XMLHttpRequest inherit from. We can leverage it in our own code as well and inherit from it: class MyClass extends EventTarget { ... }. When we construct our own EventTarget, all event dispatched through it are done synchronously like node.js or other libraries but unlike the DOM, which emits events asynchronously.</p><h3>CustomEvent</h3><p>CustomEvent is basically identical to the Event class (base class used by the DOM to emit ClickEvent s, etc) except that it allows us to attach custom data to it. So here we specify the event name and data attached to it:</p><pre>new CustomEvent(&#39;my-event&#39;, { <br>  detail: 123 <br>});</pre><p>detail can be anything you want, even another object. Sort of a strange API but that&#39;s how it was designed. If you don&#39;t have any additional information to dispatch along with your event, you can just use new Event(&#39;my-event&#39;) instead. If you want to go crazy, note that you can also extend CustomEvent and pass your subclass to EventTarget.</p><h3>Making a nicer API</h3><p>In a small amount of code, we can adapt it to a more common node.js style API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ac5fac25638e3d2e22b3396b8a87e7b/href">https://medium.com/media/1ac5fac25638e3d2e22b3396b8a87e7b/href</a></iframe><p>If I was to use this pattern in an application that’s more than a one-off project, I’d consider encapsulating it like this just in case I needed to swap out the implementation later.</p><h3>The pros and cons</h3><p>By using EventTarget, you get some interesting functionality for free that you don&#39;t get with most libraries:</p><ul><li>Events can be canceled via the familiar event.preventDefault(). This means that if one event handler cancels the event, any subsequent handlers are <em>not</em> called. This ability is configurable with the cancelable property passed to the CustomEvent constructor (see above).</li><li>once functionality (mitt doesn&#39;t have this) -- an event handler is removed once it is called once.</li><li>Duplicate events handlers aren’t added. For example, if I add the same callback listener and options multiple times, it’s only registered once. This can help prevent memory leaks for you automatically.</li><li>Sense of superiority that you didn’t bloat your bundle with yet another npm package.</li></ul><p>Some downsides though:</p><ul><li>verbose</li><li>lots of DOM related stuff around bubbling and DOM elements that don’t apply when using it like this</li><li>no IE support, and ironically, lots of legacy IE properties like srcElement and returnValue</li><li>can’t ever manually manipulate the event listener list or have a method like prependEventListener</li></ul><p>Well, this was fun. There’s a lot of interesting corners of the DOM API that are fun to explore. Even if you never use this in actual code, I think knowing about it leads to a deeper understanding of the DOM, which is valuable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b064aa2df09e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cameron-nokes/build-your-own-event-emitter-using-only-native-dom-apis-b064aa2df09e">Build your own event emitter using only native DOM APIs</a> was originally published in <a href="https://medium.com/cameron-nokes">Cameron Nokes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cancelling async tasks with AbortController]]></title>
            <link>https://medium.com/cameron-nokes/cancelling-async-tasks-with-abortcontroller-d2f62b2a924c?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2f62b2a924c</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 23:18:29 GMT</pubDate>
            <atom:updated>2019-08-26T23:18:29.540Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use AbortController as a general, standard way to abort async tasks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jUpXez9-l-6YC0Ps.jpeg" /></figure><blockquote><em>Originally published at </em><a href="https://cameronnokes.com/blog/cancelling-async-tasks-with-abortcontroller/">https://cameronnokes.com/blog/cancelling-async-tasks-with-abortcontroller/</a></blockquote><p>I learned the other day that <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController">AbortController</a> can be used to not only abort fetches, but can be used in basically any way you like. Just like promises can be used to represent any future, pending value, AbortController can be used as a controller to stop pending async operations. This was exciting to me, which I realize probably comes off sad sounding and means that I need more excitement in my life but--whatever--that&#39;s besides the point.</p><p>The typical usage of AbortController that I was aware of was using it with fetch like this:</p><pre>let abortController = new AbortController();<br>fetch(&#39;/url&#39;, { signal: abortController.signal });<em><br></em>abortController.abort();</pre><p>Calling the abort method cancels the HTTP request and rejects the promise. How exactly an AbortController.signal is consumed wasn&#39;t clear to me but it turns out it&#39;s pretty simple.</p><p>AbortControllerSignals implement the DOM&#39;s <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget">EventTarget</a> interface, or in other words, are an event emitter with an addEventListener method. This allows us to use it like this:</p><pre>let abortController = new AbortController(); abortController.signal.addEventListener(&#39;abort&#39;, (event) =&gt; {<br>  // <em>implement your canceling logic here<br></em>});</pre><p>So let’s write a function that does an async task that allows the caller to pass an AbortControllerSignal to it to cancel it. I&#39;ve occasionally had reason to create a function that basically promisifies setTimeout in actual code, so we&#39;ll use that as our example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/142e679d1ba444e94afac7ed19473e87/href">https://medium.com/media/142e679d1ba444e94afac7ed19473e87/href</a></iframe><h3>Why does this matter?</h3><p>I think there’s a lot of value in using standardized patterns. For example, Promises gave us a standard way to represent future values. There are alternatives to native Promises, some of those approaches are arguably better, but they’re not standard. Any time you consume code that uses non-standard approaches, there’s some conflict. How do I integrate this into existing code that uses different patterns? Do other people on my team need to learn new things now to properly leverage it? Or if you’re writing a library, there’s the dependency cost to consider. That’s why the idea of a standard way of aborting an asynchronous operation that’s baked into the platform seems valuable to me. Currently AbortController is a DOM only thing, but there&#39;s a <a href="https://github.com/nodejs/node/issues/19393">proposal</a> to bring fetch into Node.js, which would probably mean bringing it over there as well.</p><h3>What do you do when the async task can’t be aborted?</h3><p>Not all async operations are abortable, for example, Notification.requestPermission(), and promises don&#39;t have any sort of way to unsubscribe callbacks you&#39;ve passed to then or catch (I&#39;m not even sure that they should). This could be problematic in a use case like this that I made up:</p><pre>function requestNotificationPermission(opts = {}) { <br>  return fetch(&#39;/user/settings&#39;, { signal: opts.signal })<br>    .then(res =&gt; res.json())<br>    .then(({ canNotify }) =&gt; { <br>      if (canNotify) { <br>        return Notification. requestPermission(); <br>      } else { <br>        throw new Error() <br>      } <br>   }); <br>}</pre><pre>let abortController = new AbortController();</pre><pre>requestNotificationPermission({ signal: abortController.signal })<br>  .then(/**/)<br>  .catch(/**/);</pre><pre><em>// whenever and where ever this is called, I should be able to expect that<br>// the promise above will be rejected... but that&#39;s not the case</em></pre><pre>abortController.abort();</pre><p>In the above example, the abort() will cancel the fetch if it&#39;s in-flight, but if it&#39;s already resolved, then the promise will resolve and go on to the next call, Notification.requestPermission, where there&#39;s no way of canceling it. So the promise returned by requestNotificationPermission might resolve even though I&#39;ve aborted it. Just depends on where you are in that series of async tasks. So how do we fix that?</p><p>For this use case, this is the best I can think of:</p><pre>function requestNotificationPermission(opts = {}) { <br>  let isAborted = false; <br>  opts.signal.addEventListener(&#39;abort&#39;, () =&gt; { <br>    isAborted = true; <br>  }); <br>  return fetch(&#39;/user/settings&#39;, { signal: opts.signal }) <br>    .then(res =&gt; res.json())<br>    .then(({ canNotify }) =&gt; { <br>      if (canNotify) { <br>        return Notification.requestPermission(); <br>      } else { <br>        throw new Error(); <br>      } <br>    }) <br>    .then(result =&gt; { <br>      if (isAborted) { <br>        throw new Error(); <br>      } else { <br>        return result; <br>      } <br>    }); <br>}</pre><h3>Conclusion</h3><p>While the using AbortController is a bit clunky, I appreciate that it provides a standardized, composable solution to cancel async tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2f62b2a924c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cameron-nokes/cancelling-async-tasks-with-abortcontroller-d2f62b2a924c">Cancelling async tasks with AbortController</a> was originally published in <a href="https://medium.com/cameron-nokes">Cameron Nokes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with JSON in bash using `jq`]]></title>
            <link>https://medium.com/cameron-nokes/working-with-json-in-bash-using-jq-13d76d307c4?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/13d76d307c4</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Mon, 16 Jul 2018 18:01:01 GMT</pubDate>
            <atom:updated>2019-08-10T23:34:16.036Z</atom:updated>
            <content:encoded><![CDATA[<h4>jq is a powerful tool that lets you read, filter, and write JSON in bash</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvE6hcrDYgjIjsL-7RHxRg.png" /></figure><blockquote>Originally published on <a href="https://cameronnokes.com/blog/working-with-json-in-bash-using-jq/">https://cameronnokes.com/blog/working-with-json-in-bash-using-jq/</a></blockquote><p>Perhaps you’ve seen or even written bash that looks like this:</p><pre>curl -s &quot;<a href="http://api.icndb.com/jokes/random">http://api.icndb.com/jokes/random</a>&quot; \<br>| python -m json.tool \<br>| grep &#39;\&quot;joke\&quot;&#39; \<br>| cut -d &#39;:&#39; -f 2 \<br>| sed &#39;s/&amp;quot;/\&quot;/g&#39;</pre><p><em>(Note: the above code was taken from </em><a href="https://hackernoon.com/a-crude-imessage-api-efed29598e61"><em>https://hackernoon.com/a-crude-imessage-api-efed29598e61</em></a><em>, which is a great article).</em></p><p>That’s tough to read and even tougher to write. You have to pipe to 4 different utilities just to get to a property in the JSON response body! Bash doesn’t understand JSON out of the box, and using the typical text manipulation tools like grep, sed, or awk, gets difficult. Luckily there’s a better way using a tool called <a href="https://stedolan.github.io/jq/">jq</a>.</p><p>jq can simplify the above bash to this:</p><pre>curl -s &quot;http://api.icndb.com/jokes/random&quot; | jq &#39;.value.joke&#39;</pre><p>That’s much nicer 😎. By making JSON easy to work with in bash, jq opens up a lot of automation possibilities that otherwise required me to write something in node.js (which isn’t bad, it just takes longer generally).</p><h3>Why not just use node.js when you need to deal with JSON?</h3><p>Sometimes node.js is the right tool. For most automation tasks, I like to use bash whenever possible because it’s faster and even more portable (I can share a bash script with team members that don’t have node.js installed). To me, bash is more expressive and succinct for certain tasks than node is.</p><h3>Install jq</h3><p>jq isn’t a built-in command in any environment, so you have to install it. Run brew install jq on macOS. See jq’s <a href="https://stedolan.github.io/jq/download/">install help page</a> for how to install on other environments.</p><h3>Basics of jq</h3><p>jq works similarly to sed or awk — like a filter that you pipe to and extract values from. Also like sed or awk, it basically has it’s own domain specific language (DSL) for querying JSON. Luckily, it’s really intuitive (unlike awk 😜).</p><h4>Get a property</h4><p>Let’s say we have JSON that looks like this:</p><pre>{ &quot;foo&quot;: 123, &quot;bar&quot;: 456 }</pre><p>To print out the foo property, we use the . operator followed by the property name.</p><pre>echo &#39;{ &quot;foo&quot;: 123, &quot;bar&quot;: 456 }&#39; | jq &#39;.foo&#39;</pre><p>That will print out 123 , as expected.</p><p>This works with nesting too. So .a.b.c.d will traverse down nested objects’ properties.</p><p>This, all by itself, is pretty useful. For a realistic and totally useful example, let’s write a script that gets the Astronomy Picture of the Day and sets it as our wallpaper (this is macOS only).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dafea7eba080dc6b4cec96c73379f3d6/href">https://medium.com/media/dafea7eba080dc6b4cec96c73379f3d6/href</a></iframe><p>Yay! All this astronomy stuff makes it feel like the right time for a Neil deGrasse Tyson gif.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZVfb8tp6iZE0E%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fneil-degrasse-tyson-cosmos-he-said-it-the-thing-ZVfb8tp6iZE0E&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZVfb8tp6iZE0E%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="217" frameborder="0" scrolling="no"><a href="https://medium.com/media/014f304ad953d6e917f8485fb244a923/href">https://medium.com/media/014f304ad953d6e917f8485fb244a923/href</a></iframe><p>Note that if a property has a spaces or weird characters in it, you’ll have to use quotes. For example:</p><pre>echo &#39;{ &quot;Version Number&quot;: &quot;1.2.3&quot; }&#39; | jq &#39;.&quot;Version Number&quot;&#39;</pre><p>Also, be sure to always wrap your jq selector in a single-quotes, otherwise bash tries to interpret all the symbols like . , whereas we want jq to do that.</p><h4>Iteration</h4><p>Now let’s see how iteration works. The array or object value iterator operator, .[] , is what makes it possible.</p><p>Here’s a really basic example:</p><pre>echo &#39;[1,2,3]&#39; | jq &#39;.[]&#39;</pre><p>That will output 1, 2, 3 on separate lines.</p><p>In an array of objects, you can access a property on each item in the array like so:</p><pre>echo &#39;[ {&quot;id&quot;: 1}, {&quot;id&quot;: 2} ]&#39; | jq &#39;.[].id&#39;</pre><p>Or on an object, .[] will output the value of each key/value pair:</p><pre>echo &#39;{ &quot;a&quot;: 1, &quot;b&quot;: 2 }&#39; | jq &#39;.[]&#39;</pre><p>So that will return 1 2.</p><p>Note that you can also pass an index to .[], so</p><pre>echo &#39;[&quot;foo&quot;, &quot;bar&quot;]&#39; | jq &#39;.[1]&#39;</pre><p>will return just bar.</p><p>Now how do we do something for each line? In the same way you’d handle anything that outputs multiple lines of information in bash: xargs , for loops, or some commands just handle multiple input items, etc. For example:</p><pre>echo &#39;[&quot;foo&quot;, &quot;bar&quot;]&#39; | jq &#39;.[]&#39; | touch</pre><h4>jq Functions</h4><p>jq also has built-in “functions”. Returning to the previous object iteration example — let’s say we wanted get the keys of the object (not the values) as an array:</p><pre>echo &#39;{ &quot;a&quot;: 1, &quot;b&quot;: 2 }&#39; | jq &#39;keys | .[]&#39;</pre><p>which will return a b . Note that we’re also using the pipe | operator, which works the same in jq as it does in bash — it takes the output from the left and passes it as input to the right.</p><p>Another handy function for arrays and objects is the length function, which returns the array’s length property or the number of properties on an object.</p><pre>echo &#39;[1,2,3]&#39; | jq &#39;length&#39;</pre><p>You can get even fancier and create intermediary arrays and objects on the fly. Here, I’m combining the keys of the dependencies and devDependencies objects (from a package.json file) into an array, flattening it, and then getting the length.</p><pre>jq -r &#39;[(.dependencies, .devDependencies) | keys] | flatten | length&#39; package.json</pre><p>That returns the number of dependencies and devDependencies a package.json contains.</p><h3>Let’s use it for real now</h3><p>What if I wanted to audit my package.json dependencies and remove anything that’s not being used? Unused dependencies slow down npm installs for everyone and is just messy. I could manually grep usages of each dependency (via grep or in my IDE), but if you have a lot of dependencies that gets tedious fast, so let’s automate it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46eb3846f96fc1f3dc1fae2f72492326/href">https://medium.com/media/46eb3846f96fc1f3dc1fae2f72492326/href</a></iframe><p>[1] Here’s how the grep flags work:</p><ul><li>--include and --exclude-dir narrow the files that get searched</li><li>-R means recursive, tells it to grep all matching files</li><li>--color colorizes the output</li><li>-n displays line numbers</li></ul><p>[2] I have to export it so that a subshell can see it. If you want xargs to call a custom function, you have to call it in a subshell for some reason</p><p>[3] -r is for “raw-output”, so no quotes around values, which makes it suitable for processing in other bash commands. We get the dependency names as an array (this is equivalent to Object.keys(require(&#39;./package.json&#39;).dependencies) in node.js)</p><p>[4] Then we pipe that to xargs which handles setting up a grep for each lines. Here’s how the xargs flags all work:</p><ul><li>-t tells it to echo the constructed command; useful for debugging</li><li>-I {} defines the replacement string where the dependency string will get placed</li><li>-P 4 defines the concurrency, so 4 concurrent greps</li><li>we tell it to start a bash subshell where our grep_dep function is called with it’s args</li></ul><p>There’s more that could be done to the grep-ing in that script to make it more robust, but that’s the basic gist.</p><p>I used something similar to this recently at work to prune unused dependencies. We have a huge front-end mono-repo with a single package.json that has 250 dependencies 🙀, so some automated assistance was necessary.</p><p>jq is awesome and makes working with JSON in bash easy. The DSL for filtering, querying, and creating JSON goes much deeper than what I’ve covered here, so see <a href="https://stedolan.github.io/jq/manual/">https://stedolan.github.io/jq/manual/</a> for the full documentation.</p><h4>Check out my bash course on egghead.io</h4><p><a href="https://egghead.io/courses/automate-daily-development-tasks-with-bash">Automate Daily Development Tasks with Bash</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13d76d307c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cameron-nokes/working-with-json-in-bash-using-jq-13d76d307c4">Working with JSON in bash using `jq`</a> was originally published in <a href="https://medium.com/cameron-nokes">Cameron Nokes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 30-second guide to publishing a TypeScript package to NPM]]></title>
            <link>https://medium.com/cameron-nokes/the-30-second-guide-to-publishing-a-typescript-package-to-npm-89d93ff7bccd?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/89d93ff7bccd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Thu, 08 Mar 2018 03:57:05 GMT</pubDate>
            <atom:updated>2019-08-10T23:36:21.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgbhz2GTZlAcfJeOvMWlkg.png" /></figure><blockquote>Originally published on <a href="https://cameronnokes.com/blog/the-30-second-guide-to-publishing-a-typescript-package-to-npm/">https://cameronnokes.com/blog/the-30-second-guide-to-publishing-a-typescript-package-to-npm/</a></blockquote><p>You already have a library/package written in TypeScript that you’re ready to publish to NPM, but you still want all the types to work and you don’t want to commit compiled JS files. This article is for you 😘.</p><p><strong>TLDR;</strong> you can see a simple example of this in action here:</p><p><a href="https://github.com/ccnokes/dom-event-utils">ccnokes/dom-event-utils</a></p><p>If you haven’t written your TS based package yet, no worries, just start with this: npm init -y and tsc --init . This generates a default package.json and tsconfig.json for you. Then, follow the steps below:</p><h4>1. Add &quot;declaration&quot;: true to your tsconfig.json</h4><p>This tells TypeScript to emit an .d.ts definitions file along with your compiled JavaScript. Note that at this point, when you run the TypeScript compiler, it will complain if you’re using a private type (i.e. not export-ed). This is because your types that are part of any public facing API (and that aren’t inline types) have to be exported so that users of your library can get type checking goodness. They don’t need to be in a separate file or anything, they just need that export keyword in front of them.</p><h4>2. Add &quot;types&quot;: &quot;index.d.ts&quot; to your package.json</h4><p>When other people import your library, this tells the TypeScript compiler where to look for your library’s types. The filename of your .d.ts file will be the same as your main entry point. So, for example in your package.json you’ll want to have something like this in there:</p><pre>&quot;main&quot;: &quot;dist/index.js&quot;,</pre><pre>&quot;types&quot;: &quot;dist/index.d.ts&quot;,</pre><p>(This also assumes your outDir in tsconfig is a folder named dist).</p><h4>3. Ensure that your dist folder is ignored in .gitignore</h4><p>We don’t want to track compiled JavaScript files in our git repository. We do, however, want them sent to NPM when we publish.</p><h4>4. Run your build</h4><p>Run tsc and whatever else to compile all your files. It might be a good idea to add a prepublish script to your package.json. Something like: &quot;prepublish&quot;: &quot;tsc&quot;</p><h4>5. Run npm publish</h4><p>Boom! You just published a TypeScript based NPM package that interops seamlessly with TypeScript and JavaScript.</p><p>If you want to verify that it works locally before you publish (this is a good idea), then in your package root, run <a href="https://docs.npmjs.com/cli/link">npm link</a> . Then go to another folder and npm link &lt;your package name&gt; . Go into a .ts file and import your package by name (just like you would normally if you had npm installed it). You should see your types coming through in your editor.</p><p>Here’s what your final package.json might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fd4905afdf246979a44d8d7f2afb8d7/href">https://medium.com/media/0fd4905afdf246979a44d8d7f2afb8d7/href</a></iframe><p>Here’s what your final tsconfig.json might look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7de2734f37dd7ef2bd3997193576ca2e/href">https://medium.com/media/7de2734f37dd7ef2bd3997193576ca2e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89d93ff7bccd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cameron-nokes/the-30-second-guide-to-publishing-a-typescript-package-to-npm-89d93ff7bccd">The 30-second guide to publishing a TypeScript package to NPM</a> was originally published in <a href="https://medium.com/cameron-nokes">Cameron Nokes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The most useful bash commands for front end development]]></title>
            <link>https://medium.com/cameron-nokes/bash-commands-ive-found-most-useful-for-front-end-development-df66c8544c96?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/df66c8544c96</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Tue, 06 Feb 2018 15:01:09 GMT</pubDate>
            <atom:updated>2019-08-10T23:37:46.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PfjONxBB_XRWMo-JM0C7sw.png" /></figure><blockquote>Originally published on <a href="https://cameronnokes.com/blog/the-most-useful-bash-commands-for-front-end-development/">https://cameronnokes.com/blog/the-most-useful-bash-commands-for-front-end-development/</a></blockquote><p>Whether it’s just for npm install or some git commands, most everyone deals with <a href="https://en.wikipedia.org/wiki/Bash_(Unix_shell)">bash</a> sometime. I’ll be honest, bash can have some weird syntax, but I still think it’s a highly useful tool and very efficient way to automate tasks. For example, react, angular, and vue all have shell scripts in their repositories. Plus, bash is available on every commonly used operating system now—it comes with macOS, most Linux distros, and now Windows via the new Linux sub-system stuff.</p><p>I’m no expert in bash, but whenever I’ve invested time into learning more about it — whether it’s just a few commands or it’s syntax, it’s always paid off for me. So I’ve compiled a list of commands or other things I’ve learned about bash that I’ve found consistently useful.</p><h3>Navigating around</h3><p>You’re probably familiar with cd (change directory), but it can get cumbersome if you want to go to a folder, run a script, and come back to where you are. pushd allows you to navigate to a directory, do work there, and then popd back to where you were originally without having to remember the path back there (like cd ../../..).</p><pre>pushd level-1/level-2<br># do work ...<br>popd <br># now we&#39;re back to the directory we started in</pre><h3>Quickly peek inside a file</h3><p>Let’s say I just want to view a file’s contents quickly. There’s a few options for this. The easiest is <a href="https://ss64.com/bash/cat.html">cat</a> which stands for concatenate but can be used to just print the contents of a file.</p><p>For example, I want to check something in the package.json file:</p><pre>cat package.json</pre><p>That prints the entire file out for me in my terminal window.</p><p>Note (in case you’re pretty new to bash/shell stuff): For the above command to work, you need to be in the same directory as package.json. Also you don’t need to type out package.json completely, start typing and then hit the Tab key as you go to get autocomplete.</p><p>Now let’s say it’s a huge file and we don’t want the whole thing printing out and cluttering the screen. Let’s use <a href="https://ss64.com/bash/less.html">less</a> for that:</p><pre>less server.log</pre><p>That’ll show the file in a scrollable overlay thing in your terminal window. Less doesn’t load the entire file into memory, so it’s fast 😎. But when you’re checking out your huge server.log file, for example, you probably care more about the end of the file than the start, right? Use the Shift+G shortcut to jump to the end of the file, and then scroll up from there. Exit less with q. To search for text in the current file when in less , you can search for text by inputting /your search here and hitting Enter .</p><h3>Opening files and folders</h3><p>Now let’s say we looked at a file, and we want to open it in an application.</p><pre>open index.js</pre><p><a href="https://ss64.com/bash/open.html">open</a> will open the file in the default application you have associated with that file. In my case, that’ll open it in my current VSCode window. Maybe we’re opening a weird file that’s not associated with any application in particular.</p><pre>open yarn.lock</pre><p>For me this returns: “No application knows how to open yarn.lock.” Let’s tell bash where we want it opened:</p><pre>open yarn.lock -a TextEdit</pre><p>Or open yarn.lock -a &quot;Visual Studio Code&quot; but that’s a lot of typing. However, if you want it in VSCode quick and easy from the command line, you can install VSCode’s command line tools and run code yarn.lock.</p><p>Another cool open trick is it can open the current directory (or any directory) in Finder:</p><pre>open .</pre><p>Or replace the . , which means the current directory, with whatever one you want. If you’re on a Windows bash emulator like Cygwin or git bash, explorer . does the same thing, but in Windows Explorer. This is especially handy for hidden folders you can’t get to in the UI, e.g. open .git .</p><h3>Create and delete directories and files</h3><p>This is bread and butter bash, so you use this all the time. So, let’s create a directory with <a href="https://ss64.com/bash/mkdir.html">mkdir</a>.</p><pre>mkdir my-folder</pre><p>Cool, I love how you just created that folder for me, bash. Now let’s create folders several levels deep and let bash handle creating ones that don’t exist as it goes.</p><pre>mkdir -p level1/level2/level3/level4</pre><p>Without the -p , mkdir will fail on non-existent directories. Now let’s delete them all with <a href="https://ss64.com/bash/rm.html">rm</a>.</p><pre>rm -rf level1</pre><p>The -r stands for recursive and the -f for force. That way bash knows to delete everything in that directory and everything below it and not to prompt me for confirmation when deleting files.</p><p>Now let’s create an empty file. There’s a few ways to do this. I usually use <a href="http://man7.org/linux/man-pages/man1/touch.1.html">touch</a>.</p><pre>touch myfile.js</pre><p>But I just learned that good ol’ <a href="https://ss64.com/bash/echo.html">echo</a> does the job even better (I think).</p><pre>echo &gt; myfile.js</pre><p>That creates an empty file, which is nice sometimes. (You can read up on how the <a href="https://unix.stackexchange.com/questions/283374/what-does-the-left-chevron-triangle-bracket-do">angle bracket operator</a> works here). Now let’s create a file and initialize it with something.</p><pre>echo &quot;console.log(&#39;hey hey&#39;)&quot; &gt; index.js</pre><p>Oh, nice.</p><h3>Finding files and searching text in files</h3><p>You’re trying to find that one file, what was it called again?</p><pre>find . -name &quot;*part-of-the-filename*.js&quot;</pre><p>The name parameter isn’t a regex, but it accepts and matches on some special characters, like the wildcard *.</p><p>You can tell <a href="https://ss64.com/bash/find.html">find</a> to do stuff with the files it finds too. Let’s say I need to delete a bunch of log files. find makes this easy.</p><pre>find . -name &quot;*.log&quot; -delete</pre><p>Now, let’s say I want to move all my unit test files to a separate folder, for some reason.</p><pre>find some-folder -name &quot;*.test.js&quot; -exec mv {} tests \;</pre><p>The -exec param takes an arbitrary command, executes it for each file it found, and substitutes {} with the filename. -exec has to end with a ; , which has to be escaped, hence the \; weirdness at the end. The syntax is weird at first but when you do it a few times, you forget about it and just appreciate how fast that was compared to using the UI or writing a node.js script to do it.</p><p>In order to find content in files, we can use <a href="https://ss64.com/bash/grep.html">grep</a>. Grep can get complicated with lots of flags quickly, but this is fairly simple and useful:</p><pre>grep . -Re &quot;regex pattern here&quot;</pre><p>That recurses (-R) from the current directory and searches all files for a regex match (-e standing for regex pattern). That outputs the file the match was found in as well as the text it matched. Grep gets more useful if you add more flags to it. Let’s tells it to output the line number in the file the match was found on, ignore case, and colorize the match. So if I wanted to find all instances of require(&#39;lodash&#39;) or require(&quot;lodash/debounce&quot;) in a project:</p><pre>grep -Rnwi -C 1 --color . -e &quot;require(.*lodash.*)&quot;</pre><p>…but that’s a lot of typing, which leads me to my next point…</p><h3>Alias long commands</h3><p>Let’s alias that last grep command. Open your bash_profile (usually located at your user home directory, ~/.bash_profile , you can create it if it doesn’t exist) and add to that file:</p><pre>alias codegrep=&quot;grep -Rnwi -C 1 --color . -e $1&quot;</pre><p>The $1 gets replaced with the first argument that you pass when you invoke the alias. Now we can codegrep &quot;require(.*lodash.*)&quot; and it works just the same as before. Cool.</p><p>One of the most useful aliases that I have is this one:</p><pre>alias json=&quot;cat $1 | python -m json.tool&quot;</pre><p>That takes a JSON string and formats it using Python’s <a href="https://docs.python.org/3/library/json.html#module-json.tool">json.tool</a> (Python is shipped with macOS, no installation necessary). For example:</p><pre>curl https://pokeapi.co/api/v2/pokemon/1/ | json</pre><p>Much easier to read than the wall of unformatted JSON string that you get without it. (You can read up on the <a href="https://superuser.com/a/756259/403680">pipe operator</a> | if that’s new to you).</p><h3>History</h3><p>Forget a long command that you did last week? Bash saves every command you run in a history which you can access via <a href="https://ss64.com/bash/history.html">history</a>. So maybe you ran a complicated webpack command using the webpack-cli and can’t remember it.</p><pre>history | grep webpack</pre><p>You can grep your bash history to quickly find it. Note that your history is capped, so anything too old gets dropped off the list.</p><h3>Kill runaway processes</h3><p>Maybe you started a node HTTP server that’s listening on port 9000 and you thought you closed it out, but when you try to start a new server at port 9000 you get an “address in use” error (EADDRINUSE). So somehow it’s still running somewhere?</p><p>First, let’s find the process id that is listening on that port with <a href="https://en.wikipedia.org/wiki/Lsof">lsof</a>.</p><pre>lsof -i:9000</pre><p>That’ll output a little table that includes the process id. Now let’s shut down the process with the aptly named <a href="https://ss64.com/bash/kill.html">kill</a>.</p><pre>kill &lt;process id here&gt;</pre><p>This might seem esoteric but it’s come up for me a number of times. Just skip this if it’s never happened to you.</p><h3>I forgot some flags for this command I’m trying to run</h3><p>Luckily, you can access bash’s manual from bash itself.</p><pre>man &lt;command name here&gt;</pre><p>This brings up a less like window overlay thing with all the documentation and usually some examples for the command. man stands for manual. Even faster than googling.</p><h3>Create a script out of some bash</h3><p>Let’s say you have a recurring task you’ve automated with some bash. Let’s create an executable bash script and then run it from the command line.</p><p>First, let’s create our script file (do this however you want).</p><pre>echo &quot;echo hello from bash&quot; &gt; script.sh</pre><p>Now we need to be able to execute this file from bash so we need to change permissions.</p><pre>chmod +x script.sh</pre><p>Now let’s run it</p><pre>./script.sh</pre><p>The <a href="https://stackoverflow.com/questions/6331075/why-do-you-need-dot-slash-before-executable-or-script-name-to-run-it-in-bas">dot slash</a> tells bash to evaluate and run your script as if it had been typed out from your terminal.</p><h3>Repeat last command with sudo</h3><p>You’re trying to add an entry to /etc/hosts or something which requires privileges. Your command doesn’t work without sudo , but instead of retyping it all out, you can just sudo !! .</p><h3>Background tasks</h3><p>Sometimes I rm -rf a huge folder (like node_modules or something) and then sort of regret it because now that terminal tab is locked up until that command completes. Luckily, backgrounding tasks in bash is easy.</p><pre>rm -rf node_modules &amp;</pre><p>The &amp; tells it to execute in the background, so after you run that, your shell will immediately return control to you so you can keep working. It’ll notify you when it’s complete too.</p><p>The same &amp; operator can be used to parallelize tasks. Let’s say in a script we want to do two things that take a long time but can be run in parallel.</p><pre>zip -r big.zip large-dir &amp;</pre><pre>zip -r big2.zip other-large-dir &amp;</pre><h3>Conclusion</h3><p>Spending a little time to learn bash is time well-spent, even for a front-end developer. This list, by the way, is in no way exhaustive, as there’s so much you can do with bash. These are just the commands I’ve found myself reaching for the most. To recap them all in order:</p><ul><li>pushd</li><li>popd</li><li>cat</li><li>less</li><li>open</li><li>mkdir</li><li>rm</li><li>touch</li><li>echo</li><li>find</li><li>grep</li><li>alias</li><li>history</li><li>lsof</li><li>kill</li><li>man</li><li>chmod</li></ul><p>Happy bashing 😁.</p><h3>Side note: How are all these shell commands implemented?</h3><p>This probably depends on lot on your operating system. Most of the bash commands I referenced above that aren’t shell “built-ins” (like cd) can be found here in <a href="https://github.com/coreutils/coreutils/tree/master/src">GNU’s coreutils repository</a> and are implemented in C. I imagine most implementations look like those. Of course, anything in /bin (among other directories), can be executed as a command from bash, and can be implemented in any language you like. It’s also worth noting that many bash commands are just a CLI for C API functions (like mkdir).</p><h4>Check out my bash course on egghead.io</h4><p><a href="https://egghead.io/courses/automate-daily-development-tasks-with-bash">Automate Daily Development Tasks with Bash</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df66c8544c96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cameron-nokes/bash-commands-ive-found-most-useful-for-front-end-development-df66c8544c96">The most useful bash commands for front end development</a> was originally published in <a href="https://medium.com/cameron-nokes">Cameron Nokes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Common Mistakes Front End Developers Make When Using `fetch`]]></title>
            <link>https://medium.com/cameron-nokes/4-common-mistakes-front-end-developers-make-when-using-fetch-1f974f9d1aa1?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f974f9d1aa1</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Tue, 09 Jan 2018 04:56:07 GMT</pubDate>
            <atom:updated>2019-08-10T23:38:11.402Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTW9abjNPOx4Pa5cZm9ZUA.png" /><figcaption>I felt obligated to make the Mean Girls reference</figcaption></figure><blockquote>Originally published on <a href="https://cameronnokes.com/blog/4-common-mistakes-front-end-developers-make-when-using-fetch/">https://cameronnokes.com/blog/4-common-mistakes-front-end-developers-make-when-using-fetch/</a></blockquote><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">fetch</a> is the hot new way to make HTTP requests in the browser. More than just being a better, more ergonomic API than <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a>, it brings a lot of exciting new capabilities like response streaming, more control over credentials and CORS requests, and integration with ServiceWorkers and the Cache API.</p><p>As I’ve researched fetch, used it, and seen it used in the wild, I’ve found that there’s a lot of common errors that even really experienced developers make. I think much of this has to do with the fact that fetch’s API, on the surface, looks and behaves much like jQuery’s <a href="http://api.jquery.com/jquery.ajax/">$.ajax</a>, angularJS’s <a href="https://docs.angularjs.org/api/ng/service/$http">$http</a>, <a href="https://github.com/axios/axios">axios</a>, and others. There’s some important differences and most of those differences stem from fetch’s design as a low-level network request primitive.</p><h3><strong>1. Assuming that the promise rejects on HTTP error statuses</strong></h3><p>Fetch is promise based, so it’s easy to assume that it will reject it’s promise if it receives an HTTP error status, like 404 or 500. Just like raw XMLHttpRequest, that’s not the case with fetch — it only rejects it’s promise on a “network error” (sort of a confusing term, but that’s what the spec says). If you get an http error from a server, the server is working and actively processing requests, so a network error represents when the server can’t be reached at all (e.g connection refused or name not resolved) or there’s an error with the request configuration, for example.</p><p>For example, the ftp protocol is not supported by fetch so this will return a rejected promise:</p><pre>fetch(&#39;ftp://example.com&#39;)<br>  .catch(err =&gt; console.error(&#39;Caught error: &#39;, err))</pre><p>But requesting a URL from a server that will return a 404 will not fail.</p><pre>fetch(&#39;https://jsonplaceholder.typicode.com/404&#39;)<br>  .then(res =&gt; console.log(&#39;response: &#39;, res))<br>  .catch(console.error)</pre><p>I think most developers find it useful in web applications to reject a promise if an HTTP error status is returned. To do that, we just need to check the ok property and reject if it’s false.</p><pre>fetch(&#39;https://jsonplaceholder.typicode.com/404&#39;)<br>  .then(res =&gt; {<br>    if(res.ok) {<br>      return res;<br>    } else {<br>      throw Error(`Request rejected with status ${res.status}`);<br>    }<br>  })<br>  .catch(console.error)</pre><h3><strong>2. Forgetting to include credentials</strong></h3><p>Unlike XHR, fetch does not include any cookies in the request by default. So if requests against your API require cookie based authorization (most web apps do) this has to be there or your call will likely return 401 Unauthorized.</p><p>This is easy:</p><pre>fetch(&#39;/url&#39;, { credentials: &#39;include&#39; })</pre><p>Note that if you’re using the fetch polyfill, you can (unfortunately) accidentally forget this and everything will still work like you’re passing credentials: &#39;include&#39;. This is because it’s just using XHR under the hood, which has this behavior automatically.</p><h3><strong>3. Forgetting to set the `Content-Type` to `application/json` when POSTing JSON</strong></h3><p>$http, axios, and others tend to default to setting this header for you, so it’s easy to forget.</p><pre>fetch(&#39;https://cameronnokes.com/slack-ron-swanson-quote-bot/ron&#39;, { <br>  method: &#39;POST&#39;, <br>  body: JSON.stringify({text: &#39;bacon&#39;}), <br>  headers: {&#39;Content-Type&#39;: &#39;application/json&#39;}<br>})<br>.then(res =&gt; res.json())<br>.then(console.log)</pre><p>(This API is a part of my <a href="https://cameronnokes.com/slack-ron-swanson-quote-bot">Ron Swanson quote slack bot</a> and does actually work)</p><p>If you don’t include that header, your server might return a 400 Bad Request because the endpoint doesn’t support a plain/text content type or it just won’t be able to process the body. It depends on your API’s implementation. Regardless, your API will probably return an HTTP error status.</p><h3><strong>4. Manually writing out complicated query params in a string</strong></h3><p>I’ve seen code like this:</p><pre>fetch(&#39;/endpoint?foo=${n &gt; 1 ? 123 : 456}&amp;bar=abc&amp;query=${encodeURIComponent(someString || &#39;&#39;)}</pre><p>That’s not completely terrible or anything, but I think it could be easier to read and less error prone if we let the new <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams">URLSearchParams</a> class and a dash of lodash do a bit more work for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e7c9b461a8f8b44b3ea8956e6ea3d62/href">https://medium.com/media/9e7c9b461a8f8b44b3ea8956e6ea3d62/href</a></iframe><p>The URLSearchParams class is great and handles encoding everything properly, joining an object into a string, etc. I think that’s easier to read and easier to maintain.</p><h3>Conclusion</h3><p>Fetch is awesome but enjoy responsibly :)</p><h4>If you enjoy tweets about JavaScript (you know you do), you can follow me here <a href="https://twitter.com/ccnokes">https://twitter.com/ccnokes</a>.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f974f9d1aa1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cameron-nokes/4-common-mistakes-front-end-developers-make-when-using-fetch-1f974f9d1aa1">4 Common Mistakes Front End Developers Make When Using `fetch`</a> was originally published in <a href="https://medium.com/cameron-nokes">Cameron Nokes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AngularJS’s super secret $http caching abilities]]></title>
            <link>https://medium.com/cameron-nokes/angularjss-super-secret-http-caching-abilities-8cec7bc4fad8?source=rss-718683c9a8c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cec7bc4fad8</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Cameron Nokes]]></dc:creator>
            <pubDate>Mon, 21 Aug 2017 04:02:32 GMT</pubDate>
            <atom:updated>2017-10-13T13:56:16.950Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to customize $http’s built-in caching functionality</h4><p>Actually, it’s not secret — it’s <a href="https://docs.angularjs.org/api/ng/service/$http#caching">documented right here</a>. Although, I find that not a lot of people know about that feature. But there’s more to it than is documented there, so don’t worry, keep reading 😀.</p><p>Basically, you can do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/276f390085639d3272d61b0e2c02dc91/href">https://medium.com/media/276f390085639d3272d61b0e2c02dc91/href</a></iframe><p>…and get some caching for free. Easy!</p><p>Passing the cache: true property tells angularJS to cache the response in a cache created by $cacheFactory. (See the angularJS <a href="https://github.com/angular/angular.js/blob/a784fab605d825f1158c6292b3c42f8c4a502fdf/src/ng/http.js#L392">source for that here</a>). That cache is an <a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU">LRU (least recently used) cache</a> with no limit to it’s capacity.</p><p>The $http cache will cache the promise created before the underlying XMLHttpRequest is sent, so if you make the same request again before the request has resolved, it returns the cached promise. Consequently, an identical, duplicate request is not made. This is pretty handy for a number of situations and provides an easy perf win for the front-end and the back-end.</p><p>But a cache that grows infinitely with every request to a unique URL? That doesn’t sound so great, so luckily we can configure it a bit by passing our own cache to that property, like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/159362e8fa3c505f539e1d755ee84a8a/href">https://medium.com/media/159362e8fa3c505f539e1d755ee84a8a/href</a></iframe><p>That cache is now no longer global to all $http requests and will only hold up to 10 items in it at a time.</p><h4>Side note: how do LRU caches work?</h4><p>An LRU cache deletes the least recently used item after it has met it’s capacity. It’s usually implemented with a <a href="https://en.wikipedia.org/wiki/Doubly_linked_list">doubly linked list</a> where the most recently used item, whether it’s new or already in the cache, is moved to the front. Items not used recently, gradually move further back in the list. When it has met it’s capacity, it removes the tail item from the list. That’s how it works in <a href="https://github.com/angular/angular.js/blob/ddb4ef13a9793b93280e6b5ab2e0593af1c04743/src/ng/cacheFactory.js#L90">angularJS</a> and in a popular node.js implementation, <a href="https://github.com/isaacs/node-lru-cache/blob/master/index.js">lru-cache</a>.</p><p>But what if I wanted to cache some data for awhile, but not indefinitely, and expire it after some time?</p><p>You can provide your own cache implementation to $http and pass it to the cache property. Let’s see what an implementation of a cache that expires entries after 5 seconds would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/078c620e90fa9fb96e96fc88c6ff1ec2/href">https://medium.com/media/078c620e90fa9fb96e96fc88c6ff1ec2/href</a></iframe><p>So basically I’m implementing the same interface that caches created via $cacheFactory do, and providing that to $http instead. AngularJS calls all the methods on it just as you’d expect because the interface is the same. Cool! AngularJS should have had that in their docs for all these years.</p><p>There are definitely other ways to achieve this kind of caching in angularJS, such as by wrapping the $http request. I like this approach better because it’s easier to reuse and drop-in to existing implementations.</p><p>There you have it! AngularJS’s $http cache property can work with any object that fulfills the $cacheFactory interface.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cec7bc4fad8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cameron-nokes/angularjss-super-secret-http-caching-abilities-8cec7bc4fad8">AngularJS’s super secret $http caching abilities</a> was originally published in <a href="https://medium.com/cameron-nokes">Cameron Nokes</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>