<?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 Andrew Dillon on Medium]]></title>
        <description><![CDATA[Stories by Andrew Dillon on Medium]]></description>
        <link>https://medium.com/@andrewjdillon?source=rss-fd4e2f8bc624------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IE5qsFYEcJuutiflxzoQcw.jpeg</url>
            <title>Stories by Andrew Dillon on Medium</title>
            <link>https://medium.com/@andrewjdillon?source=rss-fd4e2f8bc624------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:49:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrewjdillon/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[The JavaScript Execution Model]]></title>
            <link>https://javascript.plainenglish.io/the-javascript-execution-model-part-2-467c7b9b42fa?source=rss-fd4e2f8bc624------2</link>
            <guid isPermaLink="false">https://medium.com/p/467c7b9b42fa</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrew Dillon]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 23:20:25 GMT</pubDate>
            <atom:updated>2021-03-12T13:59:52.562Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Part 2: How Promises interact with JavaScript’s Call Stack and Event Loop</em></h4><p><em>The animated visualizations in this post were created with </em><a href="https://jsv9000.app/"><em>https://jsv9000.app</em></a><em> — a tool designed to help you visualize and learn about the Event Loop.</em></p><p>In the previous post, we learned about JavaScript’s Call Stack and Event Loop. We worked through an example that used setTimeout() to break a long-running synchronous function into a series of short tasks. But why did we choose setTimeout()? Could we have used Promise.resolve() instead? After all, Promises are supposed to be asynchronous, and all async JavaScript works by enqueuing tasks in the Event Loop.</p><p>Let’s try it!</p><h3>setTimeout() vs. Promise.resolve()</h3><p>We’ll use the webpage we created in part 1 to test our theory.</p><p>This was the final version of our computePrimes() function:</p><pre><strong>function</strong> computePrimes(onPrime, startAt = 2) {<br>  <strong>let</strong> currNum = startAt;<br>  <strong>while</strong> (<strong>true</strong>) {<br>    <strong>if</strong> (isPrime(currNum)) onPrime(currNum);<br>    currNum += 1;<br>    <strong>if</strong> (currNum % 500 === 0) <strong>break</strong>;<br>  }<br>  setTimeout(() =&gt; computePrimes(onPrime, currNum), 0); <em>// Magic‽</em><br>}</pre><p>Let’s rewrite it to use Promise.resolve() instead of setTimeout():</p><pre><strong>function</strong> computePrimes(onPrime, startAt = 2) {<br>  <strong>let</strong> currNum = startAt;<br>  <strong>while</strong> (<strong>true</strong>) {<br>    <strong>if</strong> (isPrime(currNum)) onPrime(currNum);<br>    currNum += 1;<br>    <strong>if</strong> (currNum % 500 === 0) <strong>break</strong>;<br>  }<br>  <em>// Let&#39;s try Promise.resolve() instead of setTimeout()</em><br>  Promise.resolve().then(() =&gt; computePrimes(onPrime, currNum));<br>}</pre><p>Now, open the webpage in your browser and click the “Start Computing Primes” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gf1jKWGE458QK5n23B29gg.png" /><figcaption><em>Webpage after running for a short time using Promise.resolve()</em></figcaption></figure><p>It doesn’t work! Maybe Promise.resolve() isn’t actually asynchronous after all? Let’s check and see:</p><pre><strong>function</strong> logA() { console.log(&#39;A&#39;); }<br><strong>function</strong> logB() { console.log(&#39;B&#39;); }<br><strong>function</strong> logC() { console.log(&#39;C&#39;); }<br><br>logA();<br>Promise.resolve().then(logB);<br>logC();<br><br><em>// =&gt; A C B</em></pre><p>Try running this yourself. You’ll see that B is <strong>always</strong> logged last. This is the same behavior we saw in part 1 from setTimeout(). So, we’ve confirmed that Promise.resolve() is, in fact, asynchronous. It’s enqueuing tasks like setTimeout() does.</p><p>But when we try to break up our computePrimes() function using Promise.resolve() instead of setTimeout(), it doesn’t work! Why‽</p><p>Clearly, setTimeout() and C are similar, but also different in some fundamental way. Let’s try tweaking our previous script to get a better handle on how they each behave:</p><pre><strong>function</strong> logA() { console.log(&#39;A&#39;) }<br><strong>function</strong> logB() { console.log(&#39;B&#39;) }<br><strong>function</strong> logC() { console.log(&#39;C&#39;) }<br><strong>function</strong> logD() { console.log(&#39;D&#39;) }<br><br>logA();<br>setTimeout(logB, 0);<br>Promise.resolve().then(logC);<br>logD();<br><br><em>// =&gt; A D C B</em></pre><p>The two synchronous calls ( logA() and logD()) are executed first, as expected. But the two async calls we made with setTimeout() (logB()) and Promise.resolve() (logC()) are logged out of order. The task enqueued by Promise.resolve() is always executed before the task enqueued by setTimeout().</p><p>This doesn’t make sense, because the Event Loop processes tasks in the Task Queue in FIFO order. And since setTimeout() ran first in our script, we’d expect its task to be executed first. But it clearly isn’t.</p><p>The understanding we gained in part 1 about the Call Stack and Event Loop can’t explain what is going on here. In order to understand why setTimeout() and Promise.resolve() behave differently, we’ll have to talk about <strong>Microtasks</strong>. But before we get to that, we need to flesh out our understanding of <strong>Tasks</strong> and the <strong>Task Queue</strong> a bit.</p><h3>Tasks</h3><p>We introduced the Task Queue as part of the Event Loop in part 1. It was presented as a single FIFO queue of Tasks. However, this picture is incomplete. In fact, the Event Loop contains <em>several</em> Task Queues.</p><p>The JavaScript language specification allows JS engines to have as many queues as they want. But there are <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#table-26">2 required queues</a>:</p><ul><li><strong>Script Task Queue</strong> — this queue contains tasks that validate and evaluate JavaScript source code. We won’t discuss this queue further in this post.</li><li><strong>Promise Task Queue</strong> — this queue contains tasks that were enqueued after a Promise was resolved or rejected. For example, you can place tasks in this queue using Promise.resolve().then(taskFn).</li></ul><p>JS engines usually have additional queues as well. For example, a browser might have a third queue for DOM events, and a fourth for timer callbacks.</p><p>The JavaScript specification doesn’t dictate the order in which these queues are to be serviced. This is left up to the designers of the JavaScript engine to decide. An engine might choose to handle all the events in its timer queue first, and only move onto the DOM event queue when the timer queue is empty. Or, the engine might interleave events from both queues.</p><p>It is also left to the engine designers to decide what happens when all event queues are empty. An engine might choose to exit (like NodeJS) or continue running and wait for some outside source to enqueue a new event (like web browsers).</p><p>Let’s model our updated version of the Event Loop in JS code:</p><pre><strong>while</strong> (EventLoop.waitForTask()) {<br>  <strong>const</strong> taskQueue = EventLoop.selectTaskQueue();<br>  <strong>if</strong> (taskQueue.hasNextTask()) {<br>    taskQueue.processNextTask();<br>  }<br><br>  rerender();<br>}</pre><p>Let’s also update our Event Loop diagram from part 1 to include additional Task Queues:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rvQUjZ54pnuljDA1qyea-Q.png" /><figcaption><em>The JavaScript Event Loop with Multiple Task Queues</em></figcaption></figure><h3>Something Smells Fishy 🐟</h3><p>The HTML specification outlines a 9 step <a href="https://www.w3.org/TR/html52/webappapis.html#event-loops-processing-model">processing model for the Event Loop</a> in browsers:</p><blockquote>An event loop must continually run through the following steps for as long as it exists:</blockquote><blockquote>1. <strong>Select the oldest task on one of the event loop’s task queues.</strong><br>2. Set the event loop’s currently running task to the task selected in the previous step.<br>3. <strong>Run the selected task.</strong><br>4. Set the event loop’s currently running task back to null.<br>5. Remove the task that was run in step 3 from its task queue.<br>6. Perform a microtask checkpoint.<br>7. <strong>Update the rendering.</strong><br>8. <em>…Omitted (this step only applies for Web Workers)…</em><br>9. <strong>Return to the first step of the event loop.</strong></blockquote><p>This is important, because according to this model, the browser should re-render in-between processing tasks.</p><p>Something doesn’t add up here. If Promise.resolve() and setTimeout() both enqueue tasks, then they should be equivalent as far as our computePrimes() function is concerned: computePrimes() should be able to break up its prime computations into a series of tasks in either the Promise or Timer Task Queues. And in between running these tasks, the Event Loop should allow the browser to re-render (step 7). But we’ve shown that this only works for the Timer Task Queue. Based on our experiment earlier, the browser does <strong>not</strong> re-render in-between processing tasks from the Promise Task Queue.</p><p>So what gives?</p><h3>A Willful Violation</h3><p>This discrepancy is due to something the HTML spec calls <strong>Microtasks</strong>. But Microtasks aren’t mentioned anywhere in the JavaScript spec. So then, where do they come from? The HTML spec has a <a href="https://www.w3.org/TR/html52/webappapis.html#integration-with-the-javascript-job-queue">section</a> that talks about this (note that the term “job” in this excerpt is what we’ve been calling a “task”):</p><blockquote>The JavaScript specification defines the JavaScript job and job queue abstractions in order to specify certain invariants about how promise operations execute with a clean JavaScript execution context stack and in a certain order. However, as of the time of this writing the definition of EnqueueJob in that specification are [sic] not sufficiently flexible to integrate with HTML as a host environment.</blockquote><blockquote><strong><em>NOTE</em></strong><em>: </em>This is not strictly true. It is in fact possible, by taking liberal advantage of the many “implementation defined” sections of the algorithm, to contort it to our purposes. However, the end result is a mass of messy indirection and workarounds that essentially bypasses the job queue infrastructure entirely, albeit in a way that is technically sanctioned within the bounds of implementation-defined behavior. We do not take this path, and instead introduce the following willful violation.</blockquote><blockquote>As such, user agents must instead use the following definition in place of that in the JavaScript specification. These ensure that the promise jobs enqueued by the JavaScript specification are properly integrated into the user agent’s event loops.</blockquote><p>That was a lot of words. The HTML spec is basically saying that a particular section of the JS spec makes it hard for the HTML spec to do its job. So instead of trying to work around that section, the HTML spec just came up with its own version.</p><p>Interesting! The HTML spec intentionally violates the JavaScript spec. This violation is where Microtasks come from.</p><p>As a result of this violation, the picture we formed earlier in this post about the Promise Task Queue isn’t really correct¹. None of the major JS engines have a Promise Task Queue. Instead, they have a Microtask Queue. Tasks that would have gone to the Promise Task Queue go here instead, and are called <strong>Microtasks</strong>.</p><h3>Microtasks</h3><p><strong>Microtasks</strong> are a lot like <strong>Tasks</strong>. They are synchronous blocks of code (think of them as Function objects) that have exclusive access to the Call Stack while running. And just like Tasks, Microtasks are able to enqueue additional Microtasks or Tasks to be run next.</p><p>The only difference between Microtasks and Tasks is where they are stored, and when they are processed.</p><ul><li>Tasks, as we know, are stored in Task Queues. But Microtasks are stored in the Microtask Queue (there’s only one of these).</li><li>Tasks are processed in a loop, and rendering is performed in-between tasks. But the Microtask queue is emptied out after a task completes, and before re-rendering occurs.</li></ul><p>Let’s add the microtask queue loop to our Event Loop model:</p><pre>while (EventLoop.waitForTask()) {<br>  <strong>const</strong> taskQueue = EventLoop.selectTaskQueue();<br>  <strong>if</strong> (taskQueue.hasNextTask()) {<br>    taskQueue.processNextTask();<br>  }<br><br>  <strong>const</strong> microtaskQueue = EventLoop.microTaskQueue;<br>  <strong>while</strong> (microtaskQueue.hasNextMicrotask()) {<br>    microtaskQueue.processNextMicrotask();<br>  }<br><br>  rerender();<br>}</pre><p>And we’ll update our diagram as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAafrFTxySvVgYN6Bb_XnQ.png" /></figure><h3>Why Promise.resolve() Freezes Our Webpage</h3><p>Let’s return to our example. It works great if we break apart our prime calculations using setTimeout(). But if we try to use Promise.resolve() instead, the webpage freezes again.</p><p>This happens because Promise.resolve() doesn’t enqueue a Task — it enqueues a <em>Microtask</em>. And as we saw above, the Event Loop doesn’t re-render until the Microtask Queue is empty. As a result, if the Microtask Queue is never empty, the browser will never rerender.</p><p>This is exactly what is causing our example webpage to freeze! Right before the computePrimes() function returns, it enqueues another Microtask to compute the next batch of primes. This prevents the Microtask Queue from ever being fully emptied by the Event Loop.</p><p>The reason setTimeout() works fine is because it enqueues Tasks, not Microtasks. And as explained above, the browser is able to re-render in-between processing Tasks (but not in-between Microtasks).</p><p>Let’s visualize all of this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-66xwHubxFQZpBdlJlj3Xg.gif" /><figcaption><em>Visualization of the Microtask Queue. Created with </em><a href="https://jsv9000.app/"><em>https://jsv9000.app/</em></a></figcaption></figure><p>Notice how the Event Loop gets stuck at the Run all Microtasks step. No matter how long the script runs, it will never move onto the rerender step.</p><h3>Conclusion</h3><p>Before ES6, JavaScript’s Event Loop model was relatively simple and played well with the HTML specification. But with ES6 came Promises, and with Promises came additional complexity for JavaScript’s Event Loop. The JS spec handles Promises with just another Task Queue. But the HTML spec violates the JS spec by handling Promises with a new structure: the Microtask Queue. This is how all major JavaScript engines handle Promises today.</p><p>Two obvious ways to launch an asynchronous operation in JavaScript are setTimeout(taskFn, 0) and Promise.resolve().then(microtaskFn). If you only have a basic understanding of JavaScript and its Event Loop, these approaches might appear to be equivalent. But in reality, they operate differently in some important ways due to Microtasks.</p><p>I hope this post has helped you better understand how Promises interact with JavaScript’s execution model. Thanks for reading!</p><p><em>I wrote this article in February 2019. It was originally posted </em><a href="https://qdivision.io/javascript-settimeout-an-in-depth-look-part-2/"><em>here</em></a><em>.</em></p><p><strong><em>This post builds on </em></strong><a href="https://andrewjdillon.medium.com/the-javascript-execution-model-part-1-448e62628f23"><strong><em>Part 1</em></strong></a><strong><em> by discussing how Promises interact with JavaScript’s Call Stack and Event Loop.</em></strong></p><h4>Footnotes</h4><p>[1]: Well, it <em>is</em> correct if we’re only concerned about what the JavaScript spec has to say. But all major JavaScript engines were developed for browsers (including the V8 engine used by NodeJS). As a result, these JS engines must comply with both the JS and HTML specs. And so, in practice, any JS code you write will be running in an environment that uses Microtasks.</p><h4>Additional Reading and Watching</h4><ul><li><a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">https://www.youtube.com/watch?v=8aGhZQkoFbQ</a></li><li><a href="https://blog.risingstack.com/writing-a-javascript-framework-execution-timing-beyond-settimeout/">https://blog.risingstack.com/writing-a-javascript-framework-execution-timing-beyond-settimeout/</a></li><li><a href="https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/">https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop">https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop</a></li><li><a href="https://blog.bitsrc.io/microtask-and-macrotask-a-hands-on-approach-5d77050e2168">https://blog.bitsrc.io/microtask-and-macrotask-a-hands-on-approach-5d77050e2168</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Tools/Performance/Scenarios/Intensive_JavaScript">https://developer.mozilla.org/en-US/docs/Tools/Performance/Scenarios/Intensive_JavaScript</a></li></ul><h4>Primary Sources</h4><ul><li><a href="https://www.ecma-international.org/ecma-262/9.0/index.html">JavaScript Language Specification</a></li><li><a href="https://www.w3.org/TR/html52/webappapis.html">HTML Scripting Specification</a></li></ul><h4>Secondary Sources</h4><ul><li><a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/">https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/</a></li><li><a href="https://www.quora.com/Does-JavaScript-in-the-browser-have-the-equivalent-of-process-nextTick-or-setImmediate-in-node-js-or-do-we-just-have-setTimeout">https://www.quora.com/Does-JavaScript-in-the-browser-have-the-equivalent-of-process-nextTick-or-setImmediate-in-node-js-or-do-we-just-have-setTimeout</a></li><li><a href="https://stackoverflow.com/questions/26615966/how-to-make-non-blocking-javascript-code">https://stackoverflow.com/questions/26615966/how-to-make-non-blocking-javascript-code</a></li><li><a href="http://latentflip.com/loupe/">http://latentflip.com/loupe/</a></li><li><a href="https://stackoverflow.com/questions/38752620/promise-vs-settimeout">https://stackoverflow.com/questions/38752620/promise-vs-settimeout</a></li><li><a href="https://stackoverflow.com/questions/24117267/nodejs-settimeoutfn-0-vs-setimmediatefn">https://stackoverflow.com/questions/24117267/nodejs-settimeoutfn-0-vs-setimmediatefn</a></li><li><a href="https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful">https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful</a></li><li><a href="https://esdiscuss.org/topic/the-initialization-steps-for-web-browsers#content-16">https://esdiscuss.org/topic/the-initialization-steps-for-web-browsers#content-16</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a">https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a</a></li><li><a href="https://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded/2734311#2734311">https://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded/2734311#2734311</a></li><li><a href="https://en.m.wikipedia.org/wiki/Reentrancy_(computing)">https://en.m.wikipedia.org/wiki/Reentrancy_(computing)</a></li><li><a href="https://stackoverflow.com/a/19699970">https://stackoverflow.com/a/19699970</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467c7b9b42fa" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-javascript-execution-model-part-2-467c7b9b42fa">The JavaScript Execution Model</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The JavaScript Execution Model]]></title>
            <link>https://javascript.plainenglish.io/the-javascript-execution-model-part-1-448e62628f23?source=rss-fd4e2f8bc624------2</link>
            <guid isPermaLink="false">https://medium.com/p/448e62628f23</guid>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[execution-model]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Andrew Dillon]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 23:18:28 GMT</pubDate>
            <atom:updated>2021-03-12T13:59:00.758Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: The Call Stack, the Event Loop</h4><p><em>The animated visualizations in this post were created with </em><a href="https://jsv9000.app/"><em>https://jsv9000.app</em></a><em> — a tool designed to help you visualize and learn about the Event Loop.</em></p><p>I’ve been writing JavaScript for awhile. I’ve written web services with Express, web apps with React, mobile apps with React Native, and I’ve authored libraries, such as <a href="https://github.com/Hopding/pdf-lib">pdf-lib</a>.</p><p>Recently, while working on pdf-lib, I found myself dealing with some long running synchronous code. I had optimized this code to run as fast as possible. Yet, when this code ran it would sometimes freeze the web page and cause the browser to warn users that a script was slowing it down.</p><p>I realized this function needed to be broken apart somehow. It needed to be asynchronous in order to allow other work to be done before it finished. But the function itself wasn’t doing any fundamentally asynchronous work (it didn’t make any HTTP requests or perform any file I/O).</p><p>How does one take a fundamentally synchronous task and make it asynchronous? I didn’t know how to do this. To figure it out, I spent some time learning the intricacies of setTimeout(), Promise.resolve(), the Event Loop, and JavaScript’s <a href="https://en.wikipedia.org/wiki/Execution_model">execution model</a> in general.</p><p>My goal in writing this series of posts is to share what I learned. After reading through them, I hope that you will have a much better understanding of JavaScript’s execution model, and how async JavaScript actually works under the hood.</p><h3>A Working Example</h3><p>Let’s start by writing some code to reproduce the problem I encountered while working on pdf-lib. Most of us are familiar with the <a href="https://en.wikipedia.org/wiki/Prime_number">prime number sequence</a>, so let’s write a function to compute it:</p><pre><strong>function</strong> isPrime(n) {<br>  <strong>for</strong> (<strong>let</strong> i = 2; i &lt; n; i++) {<br>    <strong>if</strong> (n % i === 0) <strong>return</strong> <strong>false</strong>;<br>  }<br>  <strong>return</strong> <strong>true</strong>;<br>}<br><br><strong>function</strong> computePrimes(onPrime, startAt = 2) {<br>  <strong>let</strong> currNum = startAt;<br>  <strong>while</strong> (<strong>true</strong>) {<br>    <strong>if</strong> (isPrime(currNum)) onPrime(currNum);<br>    currNum += 1;<br>  }<br>}</pre><ul><li>The isPrime() function is very simple. It returns true if a number is prime, and false if it isn’t.</li><li>The computePrimes() function runs indefinitely. It checks every number from 1 to infinity to see if it’s prime. Whenever one is found, it’s passed to the onPrime callback.</li></ul><p>Let’s try it out:</p><pre>computePrimes(prime =&gt; {<br>  console.log(prime);<br>});<br><em>// =&gt; 1 2 3 5 7 11 13 ...</em></pre><p>(If you run this in a Node REPL, you’ll have to ctrl-c to stop it. In a browser, you can just close the tab)</p><p>Logging the primes is fun and all, but I’d rather see how many primes we’ve calculated instead of the values themselves. Let’s make a simple website to render a live count for us!</p><pre>&lt;!DOCTYPE html&gt;<br><strong>&lt;html&gt;</strong><br>  <strong>&lt;head&gt;&lt;meta</strong> charset=&quot;utf-8&quot; <strong>/&gt;&lt;/head&gt;</strong><br><br>  <strong>&lt;body&gt;</strong><br>    <strong>&lt;button</strong> onclick=&quot;startComputingPrimes()&quot;<strong>&gt;</strong>Start Computing Primes<strong>&lt;/button&gt;</strong><br>    <strong>&lt;div</strong> id=&quot;primes-count&quot;<strong>&gt;&lt;/div&gt;</strong><br>  <strong>&lt;/body&gt;</strong><br><br>  <strong>&lt;script</strong> type=&quot;text/javascript&quot;<strong>&gt;</strong><br>    <em>/* Insert isPrime() and computePrimes() here... */</em><br><br>    <strong>let</strong> primesCount = 0;<br>    <strong>const</strong> primesCountDiv = document.getElementById(&#39;primes-count&#39;);<br><br>    <strong>function</strong> startComputingPrimes() {<br>      computePrimes((prime) =&gt; {<br>        primesCount += 1;<br>        <strong>if</strong> (primesCount % 500 === 0) {<br>          <strong>const</strong> msg = `Total Primes Found: ${primesCount}`;<br>          primesCountDiv.textContent = msg;<br>          console.log(msg);<br>        }<br>      });<br>    }<br>  <strong>&lt;/script&gt;</strong><br><strong>&lt;/html&gt;</strong></pre><p>When you load this webpage in a browser, you’ll see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LwjM5izm7FxBKqd1_784Sg.png" /><figcaption><em>Webpage after first loading</em></figcaption></figure><p>Let’s click the “Start Computing Primes” button and see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gf1jKWGE458QK5n23B29gg.png" /><figcaption><em>Webpage after running for a short time</em></figcaption></figure><p>Oh, that’s too bad. We don’t get a live “Total Primes Found” count. Instead the browser warns us that the webpage is running slow, and gives us the opportunity to stop it.</p><p>Our code is definitely running, you can see that by the logs it’s printing. That means our primesCountDiv.textContent = msg; line is also executing. So why isn’t our primes-count div updating? And not only is our div stuck, but the button is still rendered in the pressed state! It seems like the webpage isn’t re-rendering for some reason…</p><p>Let’s see if we can fix this with some magic 🎩🐇✨. Rewrite the computePrimes() function like so:</p><pre><strong>function</strong> computePrimes(onPrime, startAt = 2) {<br>  <strong>let</strong> currNum = startAt;<br>  <strong>while</strong> (<strong>true</strong>) {<br>    <strong>if</strong> (isPrime(currNum)) onPrime(currNum);<br>    currNum += 1;<br>    <strong>if</strong> (currNum % 500 === 0) <strong>break</strong>;<br>  }<br>  setTimeout(() =&gt; computePrimes(onPrime, currNum), 0); <em>// Magic‽</em><br>}</pre><p>Now what happens when we click the “Start Computing Primes” button?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrRBBJqnca4dBg0nGcWRWQ.png" /><figcaption><em>Webpage after running with magic</em></figcaption></figure><p>It works! But why…? To answer this question, we need to talk about JavaScript’s <strong>Call Stack</strong> and <strong>Event Loop</strong>. Let’s start with the Call Stack.</p><h3>The Call Stack</h3><p>The Call Stack is a fundamental part of the JavaScript language. It is a record-keeping structure that allows us to perform function calls. Each function call is represented as a <strong>frame</strong> on the call stack. This is how the JavaScript engine keeps track of which functions have been called and in what order. The JS engine uses this information to ensure execution picks back up in the right spot after a function returns.</p><p>When a JavaScript program first starts executing, the Call Stack is empty. When the first function call is made, a new frame is pushed onto the top of the Call Stack. When that function returns, its frame is popped off of the Call Stack. Let’s look at an example.</p><p>Consider the following code snippet:</p><pre>function main() {<br>  doStuff(&#39;baz&#39;);<br>}<br><br><strong>function</strong> doStuff(x) {<br>  doThings(x);<br>  foo();<br>}<br><br><strong>function</strong> doThings(y) {<br>  console.log(&#39;Things done&#39;, y);<br>}<br><br><strong>function</strong> foo() {<br>  <strong>return</strong> &#39;bar&#39;;<br>}<br><br>main();</pre><p>Let’s look at each transition made in the Call Stack while executing the above snippet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*As8PYy4uq4RQ_vhLdV_flA.gif" /><figcaption><em>Visualization of the Call Stack. Created with </em><a href="https://jsv9000.app/"><em>https://jsv9000.app/</em></a></figcaption></figure><p>This visualization of the Call Stack is familiar to most of us. We all have an intuitive feel for what’s going on here. However, the Call Stack is only part of JavaScript’s execution model. It doesn’t tell the full story. Consider this snippet:</p><pre>function logA() { console.log(&#39;A&#39;) }<br><strong>function</strong> logB() { console.log(&#39;B&#39;) }<br><strong>function</strong> logC() { console.log(&#39;C&#39;) }<br><br>logA();<br>setTimeout(logB, 100);<br>logC();<br><br><em>// =&gt; A C B</em></pre><p>How is it that B is logged last? The Call Stack always works in order. But what we see here is happening out of order.</p><p>setTimeout is responsible for the out-of-order logging we’re seeing. What we’ve done is told JavaScript to call logB in 100 milliseconds. And because computers are fast, logC() will have been called long before 100 milliseconds have expired.</p><p>But what if we pass a timeout of 0 milliseconds?</p><pre>logA();<br>setTimeout(logB, 0);<br>logC();<br><em>// =&gt; A C B</em></pre><p>Interesting! The same thing still happens. To understand why, we need to understand what setTimeout is actually doing under the hood. Clearly, it’s not your typical function. Its behavior cannot be explained with the Call Stack alone. To explain how setTimeout works, we need to talk about the <strong>Event Loop</strong>.</p><h3>The Event Loop</h3><p>If the Call Stack keeps track of the functions that are executing right now, then the Event Loop keeps track of functions that are going to be executed in the future. The term <strong>Event Loop</strong> refers to two things:</p><ul><li>The <strong>Task Queue</strong>, which is a FIFO queue of tasks.</li><li>The looping algorithm that processes the tasks in the Task Queue.</li></ul><p><strong>Tasks</strong> are synchronous blocks of code. You can think of them as Function objects.</p><p>The Event Loop works by continuously looping through the Task Queue and processing the tasks it contains one by one. A single iteration of the Event Loop is called a <strong>tick</strong>.</p><pre>while (EventLoop.waitForTask()) {<br>  EventLoop.processNextTask();<br>}</pre><p>To process a task, the Event Loop invokes the Function associated with it. While a task is running, it has exclusive access to the Call Stack. The Event Loop waits to process the next task until the current task is finished, and the Call Stack is empty.</p><p>While a task is running, it can enqueue other tasks to be processed in subsequent ticks of the Event Loop. There are several ways to do this, the simplest of which is setTimeout(taskFn, 0). Tasks can also come from external sources such as DOM and network events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruJn_MQsIIaEDpH2eJvXsg.png" /><figcaption><em>The JavaScript Event Loop</em></figcaption></figure><p>Let’s visualize our last code snippet with a Call Stack and Task Queue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTjgOc1RWsLG5UqAKDGl7A.gif" /><figcaption><em>Visualization of the Call Stack. Created with </em><a href="https://jsv9000.app/"><em>https://jsv9000.app/</em></a></figcaption></figure><h3>One Event at a Time</h3><p>JavaScript has a single Call Stack. Because of this, the Event Loop is only allowed to process one task at a time. This makes for a relatively simple execution model that saves JavaScript from a host of concurrency issues.</p><p>Consider <a href="https://en.wikipedia.org/wiki/Reentrancy_(computing)">reentrancy</a>, defined by Wikipedia as follows:</p><blockquote>… a computer program or subroutine is called reentrant if it can be interrupted in the middle of its execution and then safely be called again (“re-entered”) before its previous invocation’s complete execution. The interruption could be caused by an internal action such as a jump or call, or by an external action such as an interrupt or signal. Once the reentered invocation completes, the previous invocations will resume correct execution.</blockquote><p>JavaScript programmers don’t have to worry about making their functions reentrant, because they can never be interrupted¹! JS functions always run to completion.</p><p>However, this simple execution model doesn’t come without risks.</p><p>Suppose a “rogue” task makes its way onto the Call Stack. This rogue task never finishes running, and occupies the Call Stack indefinitely. If this happens, the rogue task will prevent all other tasks from ever being processed. This means all other work will grind to a halt, hindering critical tasks such as rerendering!</p><p>For this reason, web browsers monitor how much time tasks spend on the Call Stack. If a task takes too long to finish, the browser alerts the user and gives them the option to “Stop It” — removing the task from the Call Stack and allowing other events to be processed.</p><h3>How our Magic Works</h3><p>Let’s return to our example. Before we added magic to it, our code was causing the webpage to freeze. And after a bit of time, the browser gave us the option to stop it. This happened because our computePrimes() function went rogue. After it was placed on the Call Stack it never finished running. It blocked the Call Stack and prevented rendering tasks from being processed.</p><p>We were able to fix this by adding some magic. Of course, it wasn’t <em>really</em> magic. And now that we’ve talked about the Call Stack and Event Loop, we can understand how it actually works.</p><p>We started with a single infinitely long task. And our magic broke it up into a series of short running tasks. Each task would compute 500 primes and then enqueue a new task to compute the next 500 primes (using setTimeout(computePrimes, 0)). This allowed the JS engine to handle other tasks that had been enqueued in-between prime calculations.</p><h3>Without Magic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9p_EzZAa4Iw1AG7jO9foZw.gif" /><figcaption><em>Visualization of Naive Primes Implementation. Created with </em><a href="https://jsv9000.app/"><em>https://jsv9000.app/</em></a></figcaption></figure><p>Notice how the Event Loop is stuck at Script Evaluation step the entire time. No matter how long the script runs, it will never move to the subsequent steps to rerender.</p><h3>With Magic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqyKb5cxGVx9aRMe6kWfLg.gif" /><figcaption><em>Visualization of Primes with Tasks Implementation. Created with </em><a href="https://jsv9000.app/"><em>https://jsv9000.app/</em></a></figcaption></figure><p>Notice how the Event Loop moves through each of its stages. After checking three numbers to see if they’re prime, a new task is enqueued and the Event Loop is able to allow rerendering.</p><h3>Conclusion</h3><p>JavaScript is a single-threaded, non-blocking, asynchronous programming language. As JavaScript developers, we deal with these language features on a daily basis. We tend to have an intuitive understanding of how to write and use async JavaScript.</p><p>However, for many of us this intuitive understanding is not backed by a strong grasp of JavaScript’s execution model and how it all works under the hood. This is unfortunate, because it can result in wasted effort over things that shouldn’t really be a concern (e.g. making functions reentrant). And it can prevent us from understanding how to troubleshoot certain performance issues (e.g. long-running synchronous functions).</p><p>I hope this post has helped you better understand JavaScript’s execution model! Please consider reading the <a href="https://andrewjdillon.medium.com/the-javascript-execution-model-part-2-467c7b9b42fa">second post</a> in this series to learn how Promises fit into the picture.</p><p><em>I wrote this article in February 2019. It was originally posted </em><a href="https://qdivision.io/javascript/"><em>here</em></a><em>.</em></p><p><strong><em>This post focused on the Call Stack and Event Loop. </em></strong><a href="https://andrewjdillon.medium.com/the-javascript-execution-model-part-2-467c7b9b42fa"><strong><em>Part 2</em></strong></a><strong><em> builds on this by discussing how Promises fit into the picture.</em></strong></p><h4>Footnotes</h4><p>[1]: This isn’t strictly true. For example, generators and recursive functions can be entered a second time before their initial invocation is complete. However, this is not a concurrency issue forced upon the developer by the runtime. So this scenario isn’t representative of the context in which reentrancy is typically a concern for developers.</p><h4>Additional Reading and Watching</h4><ul><li><a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">https://www.youtube.com/watch?v=8aGhZQkoFbQ</a></li><li><a href="https://blog.risingstack.com/writing-a-javascript-framework-execution-timing-beyond-settimeout/">https://blog.risingstack.com/writing-a-javascript-framework-execution-timing-beyond-settimeout/</a></li><li><a href="https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/">https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop">https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop</a></li><li><a href="https://blog.bitsrc.io/microtask-and-macrotask-a-hands-on-approach-5d77050e2168">https://blog.bitsrc.io/microtask-and-macrotask-a-hands-on-approach-5d77050e2168</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Tools/Performance/Scenarios/Intensive_JavaScript">https://developer.mozilla.org/en-US/docs/Tools/Performance/Scenarios/Intensive_JavaScript</a></li></ul><h4>Primary Sources</h4><ul><li><a href="https://www.ecma-international.org/ecma-262/9.0/index.html">JavaScript Language Specification</a></li><li><a href="https://www.w3.org/TR/html52/webappapis.html">HTML Scripting Specification</a></li></ul><h4>Secondary Sources</h4><ul><li><a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/">https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/</a></li><li><a href="https://www.quora.com/Does-JavaScript-in-the-browser-have-the-equivalent-of-process-nextTick-or-setImmediate-in-node-js-or-do-we-just-have-setTimeout">https://www.quora.com/Does-JavaScript-in-the-browser-have-the-equivalent-of-process-nextTick-or-setImmediate-in-node-js-or-do-we-just-have-setTimeout</a></li><li><a href="https://stackoverflow.com/questions/26615966/how-to-make-non-blocking-javascript-code">https://stackoverflow.com/questions/26615966/how-to-make-non-blocking-javascript-code</a></li><li><a href="http://latentflip.com/loupe/">http://latentflip.com/loupe/</a></li><li><a href="https://stackoverflow.com/questions/38752620/promise-vs-settimeout">https://stackoverflow.com/questions/38752620/promise-vs-settimeout</a></li><li><a href="https://stackoverflow.com/questions/24117267/nodejs-settimeoutfn-0-vs-setimmediatefn">https://stackoverflow.com/questions/24117267/nodejs-settimeoutfn-0-vs-setimmediatefn</a></li><li><a href="https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful">https://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful</a></li><li><a href="https://esdiscuss.org/topic/the-initialization-steps-for-web-browsers#content-16">https://esdiscuss.org/topic/the-initialization-steps-for-web-browsers#content-16</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5">https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5</a></li><li><a href="https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a">https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-when-you-should-use-them-a547c0757f6a</a></li><li><a href="https://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded/2734311#2734311">https://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded/2734311#2734311</a></li><li><a href="https://en.m.wikipedia.org/wiki/Reentrancy_(computing)">https://en.m.wikipedia.org/wiki/Reentrancy_(computing)</a></li><li><a href="https://stackoverflow.com/a/19699970">https://stackoverflow.com/a/19699970</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=448e62628f23" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-javascript-execution-model-part-1-448e62628f23">The JavaScript Execution Model</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</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 Create and Modify PDF Files in Deno With pdf-lib]]></title>
            <link>https://medium.com/swlh/how-to-create-and-modify-pdf-files-in-deno-ffaad7099b0?source=rss-fd4e2f8bc624------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffaad7099b0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[deno]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[https]]></category>
            <dc:creator><![CDATA[Andrew Dillon]]></dc:creator>
            <pubDate>Sun, 17 May 2020 19:12:24 GMT</pubDate>
            <atom:updated>2020-11-01T22:52:44.429Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://deno.land/">Deno</a> is an exciting new runtime for JavaScript and TypeScript. It was created by the original author of Node and corrects some <a href="https://www.youtube.com/watch?v=M3BM9TB-8yA">key mistakes</a> in Node’s design. <a href="https://deno.land/v1">Version 1.0</a> of Deno was announced just 5 days ago on May 13th, 2020.</p><p>Many developers (myself included) are very excited about Deno and the potential it has to change the JavaScript ecosystem for the better. Deno <a href="https://deno.land/v1#a-web-browser-for-command-line-scripts">strives for compatibility</a> with standard web APIs. This means that Deno does not resolve dependencies via a centralized repository such as NPM. Instead, dependencies must be <a href="https://deno.land/#third-party-modules">imported via fully qualified URLs</a>. In addition, Deno does not provide many of the APIs relied upon by NPM packages. For example, there is no global Buffer class or streams API. Under the hood Deno is written in Rust. This means that Node modules which bind to native C++ will have to be rewritten to interface with Rust APIs in order to be compatible with Deno.</p><p>The long-term payoff of these design choices will be significant. They will make it much easier to create sophisticated libraries that work both server-side and client-side. The Deno authors were very forward-looking in this respect. But reaching this end-state will take time. And, as always, the <a href="https://en.wikipedia.org/wiki/There_ain%27t_no_such_thing_as_a_free_lunch">TANSTAAFL</a><strong> </strong>principle applies here. In the short-term developers will be frustrated by <a href="https://deno.land/v1#compatibility">Deno’s incompatibility</a> with many popular NPM packages.</p><p>Processing PDF files is a very difficult task to do from scratch. As such, few developers attempt to do this without pulling in a library. NPM hosts several great libraries that make it easy to create and even modify PDF documents with JavaScript. However, not all of these libraries will work in Deno out of the box (for reasons described above).</p><p>I am the author and maintainer of <a href="https://github.com/Hopding/pdf-lib">pdf-lib</a>, an open source library for creating and modifying PDF documents. pdf-lib is written in TypeScript and compiles to pure, standard JavaScript with no native dependencies. This allows it to work in any JavaScript runtime, including web browsers, Node, React Native, and <a href="https://github.com/Hopding/pdf-lib#deno-usage">even Deno</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*BCo4eFWAc08uA8K1" /><figcaption>pdf-lib project logo</figcaption></figure><p>In the remainder of this article I will explain how to use a variety of pdf-lib features in simple Deno scripts, as well as how to serve PDFs from a Deno HTTP server.</p><p><strong>Table of Contents</strong><br>– <a href="#7014">Creating New PDFs</a><br>– <a href="#ef2e">Modifying Existing PDFs</a><br>– <a href="#0720">Embedding Fonts and Images in PDFs</a><br>– <a href="#3fc3">Serving New PDFs With HTTP</a><br>– <a href="#92b9">Serving Modified PDFs With HTTP</a><br>– <a href="#4248">Embedding Fonts and Images With HTTP</a></p><h3>Creating New PDFs</h3><p>pdf-lib makes it easy to create new PDF documents with Deno. Simply import <a href="https://pdf-lib.js.org/docs/api/classes/pdfdocument">PDFDocument</a> from the excellent <a href="https://www.skypack.dev/view/pdf-lib">Skypack CDN</a> and call a few of its methods (and a couple <a href="https://pdf-lib.js.org/docs/api/classes/pdfpage">PDFPage</a> methods). You can then serialize the PDFDocument to a Uint8Array and write it to the file system!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffbcee2d76ce593ca54fd0901b1dc0de/href">https://medium.com/media/ffbcee2d76ce593ca54fd0901b1dc0de/href</a></iframe><p>You can execute this script yourself by running:</p><pre>$ deno run --allow-write https://gist.githubusercontent.com/Hopding/8304b9f07c52904587f7b45fae4bcb8c/raw/pdf-lib-deno-create-script.ts</pre><blockquote>Note that the above script is written in TypeScript (as indicated by its .ts extension) to take full advantage of the static types provided by pdf-lib, but you can use the same code in a JavaScript (.js) file if you wish. This applies to all subsequent examples in this article as well (though you will have to remove the : ServerRequest types from the HTTP examples).</blockquote><h3>Modifying Existing PDFs</h3><p>One of the features that sets pdf-lib apart is it’s ability to <a href="https://github.com/Hopding/pdf-lib#modify-document">modify/edit existing PDF documents</a>. To use this feature you must construct an instance of PDFDocument by calling the <a href="https://pdf-lib.js.org/docs/api/classes/pdfdocument#static-load">PDFDocument.load(...)</a> method and passing in an ArrayBuffer (Uint8Arrays and base64 strings are also supported). Then you can perform all the same operations that are available on newly created PDFDocuments!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dca9d4ff7a3d32a551ca3cdbe3042cc/href">https://medium.com/media/9dca9d4ff7a3d32a551ca3cdbe3042cc/href</a></iframe><p>You can execute this script yourself by running:</p><pre>$ deno run --allow-write --allow-net https://gist.githubusercontent.com/Hopding/2d25620f0fac5cf141123129cbf0a3d8/raw/pdf-lib-deno-modify-script.ts</pre><h3>Embedding Fonts and Images in PDFs</h3><p>You can embed <a href="https://github.com/Hopding/pdf-lib#embed-font-and-measure-text">custom fonts</a>, <a href="https://github.com/Hopding/pdf-lib#embed-png-and-jpeg-images">JPG/PNG images</a>, <a href="https://github.com/Hopding/pdf-lib#draw-svg-paths">SVG paths</a>, and even <a href="https://github.com/Hopding/pdf-lib#embed-pdf-pages">PDF pages</a> with pdf-lib. The below example demonstrates how to embed fonts and images. Note that you must import pdf-lib‘s sister module, @pdf-lib/fontkit, to embed fonts (<a href="https://github.com/Hopding/pdf-lib#fontkit-installation">read about why</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8e6057bff2248b9f5cef865f899acd5/href">https://medium.com/media/b8e6057bff2248b9f5cef865f899acd5/href</a></iframe><p>You can execute this script yourself by running:</p><pre>$ deno run --allow-write --allow-net https://gist.githubusercontent.com/Hopding/29ebd6e73eb3436b94047bd29e9b9fd0/raw/pdf-lib-deno-fancy-script.ts</pre><h3>Serving New PDFs With HTTP</h3><p>The previous three examples demonstrated how to use a variety of pdf-lib features in simple scripts that write the resulting PDF directly to the filesystem. Another very common use case is producing PDFs in a server-side application. The example below creates a basic HTTP server (with Deno’s standard http module) that serves PDFs created with pdf-lib.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a0913e72c7048fe87e0cfb0d9efb4de/href">https://medium.com/media/5a0913e72c7048fe87e0cfb0d9efb4de/href</a></iframe><p>You can execute this script yourself by running:</p><pre>$ deno run --allow-net <a href="https://gist.githubusercontent.com/Hopding/c696413d6e8fef466e59604ad347efe3/raw/pdf-lib-deno-create-server.ts">https://gist.githubusercontent.com/Hopding/c696413d6e8fef466e59604ad347efe3/raw/pdf-lib-deno-create-server.ts</a></pre><p>This will start an HTTP server listening on port 8000. If you open <a href="http://localhost:8000/">http://localhost:8000</a> in your web browser you will see a PDF document (or be prompted to download one, depending on your browser and settings).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*UUknIeBIdIsP5pv83xkTjw.png" /><figcaption>New PDF loaded from <a href="http://localhost:8000/">http://localhost:8000</a> in Firefox 🦊</figcaption></figure><h3>Serving Modified PDFs With HTTP</h3><p>This example creates an HTTP server that serves a modified/edited version of an existing PDF document.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/973cb34bb03fba1354c6a1967e2fbbd4/href">https://medium.com/media/973cb34bb03fba1354c6a1967e2fbbd4/href</a></iframe><p>You can execute this script yourself by running:</p><pre>$ deno run --allow-net https://gist.githubusercontent.com/Hopding/15ca66533b11de94b4a156833a8ab6b8/raw/pdf-lib-deno-modify-server.ts</pre><p>This will start an HTTP server listening on port 8000. If you open <a href="http://localhost:8000/">http://localhost:8000</a> in your web browser you will see a PDF document (or be prompted to download one, depending on your browser and settings).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*kK4ei92JtpGk0y-F5Sa6Zg.png" /><figcaption>Modified PDF loaded from <a href="http://localhost:8000/">http://localhost:8000</a> in Firefox 🦊</figcaption></figure><h3>Embedding Fonts and Images With HTTP</h3><p>This example creates an HTTP server that serves new PDF documents with embedded fonts and images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82832d8511a80dedc7f56b3317ddf72a/href">https://medium.com/media/82832d8511a80dedc7f56b3317ddf72a/href</a></iframe><p>You can execute this script yourself by running:</p><pre>$ deno run --allow-net <a href="https://gist.githubusercontent.com/Hopding/c7adad158a01b8ee155baa415f6892a2/raw/pdf-lib-deno-fancy-server.ts">https://gist.githubusercontent.com/Hopding/c7adad158a01b8ee155baa415f6892a2/raw/pdf-lib-deno-fancy-server.ts</a></pre><p>This will start an HTTP server listening on port 8000. If you open <a href="http://localhost:8000/">http://localhost:8000</a> in your web browser you will see a PDF document (or be prompted to download one, depending on your browser and settings).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*EC7xVEP9GZw-EqwQSp--TQ.png" /><figcaption>PDF with embedded fonts and images loaded from <a href="http://localhost:8000/">http://localhost:8000</a> in Firefox 🦊</figcaption></figure><h3>Conclusion</h3><p>I hope you have found these examples to be helpful. API docs for pdf-lib can be found at <a href="https://pdf-lib.js.org/docs/api/">pdf-lib.js.org/docs/api</a>. The <a href="https://github.com/Hopding/pdf-lib/blob/master/README.md">README</a> also contains extensive documentation and usage examples. If you have any questions I encourage you to leave a comment below or <a href="https://github.com/Hopding/pdf-lib">create an issue</a> on the pdf-lib GitHub repo.</p><p>Happy hacking with Deno! 🦕 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffaad7099b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-create-and-modify-pdf-files-in-deno-ffaad7099b0">How to Create and Modify PDF Files in Deno With pdf-lib</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>