<?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 Yin Te Lan on Medium]]></title>
        <description><![CDATA[Stories by Yin Te Lan on Medium]]></description>
        <link>https://medium.com/@yinte1222?source=rss-92699a3f0a0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*49lAQg1oEyAVY985uA6lPQ.jpeg</url>
            <title>Stories by Yin Te Lan on Medium</title>
            <link>https://medium.com/@yinte1222?source=rss-92699a3f0a0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:30:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yinte1222/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[[JS] How to use Web Crypto API in web frontend (Two) — RSA asymmetric string encryption.]]></title>
            <link>https://medium.com/@yinte1222/js-how-to-use-web-crypto-api-in-web-frontend-two-rsa-asymmetric-string-encryption-9e7987bd43ab?source=rss-92699a3f0a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e7987bd43ab</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yin Te Lan]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 03:03:29 GMT</pubDate>
            <atom:updated>2023-10-19T03:03:29.345Z</atom:updated>
            <content:encoded><![CDATA[<h3>[JavaScript] How to use Web Crypto API in web frontend (Two) — RSA asymmetric string encryption and decryption.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yX8Whrfnzx-3DhI19MYaA.png" /></figure><p>In this project, methods to encrypt and decrypt string with RSA-OAEP are shown including the pem files generation. The Web Crypto API only support RSA-OAEP for RSA algorithm.</p><p>Source code:</p><p><a href="https://github.com/benjamin5252/web_crypto_api_example">GitHub - benjamin5252/web_crypto_api_example: The example code to show how to use web crypto api in a react app</a></p><p>Demo:</p><p><a href="https://benjamin5252.github.io/web_crypto_api_example/">Encryption Tool</a></p><h3><strong>1. Prepare key pair into pem string</strong></h3><p>Noted that the format name of public and private key are different.</p><pre>// utils/RSA_encryption.ts<br><br>const encryptAlgorithm = {<br>  name: &quot;RSA-OAEP&quot;,<br>  modulusLength: 2048,<br>  publicExponent: new Uint8Array([1, 0, 1]),<br>  extractable: true,<br>  hash: {<br>    name: &quot;SHA-256&quot;<br>  }<br>}<br><br>function _toPrivatePem(privateKey: ArrayBuffer) {<br>  const b64 = addNewLines(_arrayBufferToBase64(privateKey));<br>  const pem = &quot;-----BEGIN RSA PRIVATE KEY-----\n&quot; + b64 + &quot;-----END RSA PRIVATE KEY-----&quot;;<br>  <br>  return pem;<br>}<br><br>function _toPublicPem(privateKey: ArrayBuffer) {<br>  const b64 = addNewLines(_arrayBufferToBase64(privateKey));<br>  const pem = &quot;-----BEGIN PUBLIC KEY-----\n&quot; + b64 + &quot;-----END PUBLIC KEY-----&quot;;<br>  <br>  return pem;<br>}<br><br><br>export const generateRSAKeyPair = async () =&gt; {<br>  const keyPair = await window.crypto.subtle.generateKey(<br>      encryptAlgorithm,<br>      true,<br>      [&quot;encrypt&quot;, &quot;decrypt&quot;]<br>    )<br>      <br>    const keyPairPem = {<br>      publicKey: &#39;&#39;,<br>      privateKey: &#39;&#39;,<br>    }<br>    const exportedPrivateKey = await window.crypto.subtle.exportKey(<br>      &quot;pkcs8&quot;,<br>      keyPair.privateKey<br>    )<br>    keyPairPem.privateKey = _toPrivatePem(exportedPrivateKey);<br>      <br>    const exportedPublicKey = await window.crypto.subtle.exportKey(<br>      &quot;spki&quot;,<br>      keyPair.publicKey<br>    )<br>    keyPairPem.publicKey = _toPublicPem(exportedPublicKey);<br>      <br>  return keyPairPem;<br>}</pre><h3>2. Encrypt string with public key</h3><p>Noted that the public format is ‘spki’. Before every step the data need to be transfered into ArrayBuffer.</p><p>The encrypted data is exported as base64 encoded string.</p><pre>// utils/RSA_encryption.ts<br><br>function _convertPemToArrayBuffer(pem: string) {<br>  const lines = pem.split(&#39;\n&#39;)<br>  let encoded = &#39;&#39;<br>  for(let i = 0;i &lt; lines.length;i++){<br>    if (lines[i].trim().length &gt; 0 &amp;&amp;<br>        lines[i].indexOf(&#39;-----BEGIN RSA PRIVATE KEY-----&#39;) &lt; 0 &amp;&amp;<br>        lines[i].indexOf(&#39;-----BEGIN PUBLIC KEY-----&#39;) &lt; 0 &amp;&amp;<br>        lines[i].indexOf(&#39;-----END RSA PRIVATE KEY-----&#39;) &lt; 0 &amp;&amp;<br>        lines[i].indexOf(&#39;-----END PUBLIC KEY-----&#39;) &lt; 0) {<br>      encoded += lines[i].trim()<br>    }<br>  }<br>  return _base64StringToArrayBuffer(encoded)<br>}<br><br>export const encryptRsa = async (fileArrayBuffer: ArrayBuffer, pemString: string) =&gt; {<br>  <br>  const keyArrayBuffer = _convertPemToArrayBuffer(pemString);<br>  // import public key<br>  const secretKey = await crypto.subtle.importKey(&#39;spki&#39;, keyArrayBuffer, encryptAlgorithm, true, [&#39;encrypt&#39;]);<br>  // encrypt the text with the public key<br>  const ciphertextArrayBuffer = await crypto.subtle.encrypt({<br>    name: &#39;RSA-OAEP&#39;,<br>  }, secretKey, fileArrayBuffer);<br><br>  return ciphertextArrayBuffer<br>}<br><br>export const encryptStringRsa = async (str: string, pemString: string) =&gt; {<br>  // convert string into ArrayBuffer<br>  const encodedPlaintext = new TextEncoder().encode(str).buffer;<br>  const encrypted = await encryptRsa(encodedPlaintext, pemString);<br>  // store data into base64 string<br>  return _arrayBufferToBase64(encrypted);<br>};</pre><h3>3. Decrypt string with private key</h3><p>Read in the base64 encoded string to decrypt.</p><p>Noted that the inputs and ouputs of Web Crypto API are mostly ArrayBuffer.</p><p>Noted that the private key format is ‘pkcs8’.</p><pre>// utils/RSA_encryption.ts<br><br>function _convertPemToArrayBuffer(pem: string) {<br>  const lines = pem.split(&#39;\n&#39;)<br>  let encoded = &#39;&#39;<br>  for(let i = 0;i &lt; lines.length;i++){<br>    if (lines[i].trim().length &gt; 0 &amp;&amp;<br>        lines[i].indexOf(&#39;-----BEGIN RSA PRIVATE KEY-----&#39;) &lt; 0 &amp;&amp;<br>        lines[i].indexOf(&#39;-----BEGIN PUBLIC KEY-----&#39;) &lt; 0 &amp;&amp;<br>        lines[i].indexOf(&#39;-----END RSA PRIVATE KEY-----&#39;) &lt; 0 &amp;&amp;<br>        lines[i].indexOf(&#39;-----END PUBLIC KEY-----&#39;) &lt; 0) {<br>      encoded += lines[i].trim()<br>    }<br>  }<br>  return _base64StringToArrayBuffer(encoded)<br>}<br><br>export const decryptRsa = async (fileArrayBuffer: ArrayBuffer, pemString: string) =&gt; {<br>  const keyArrayBuffer = _convertPemToArrayBuffer(pemString);<br>  // import private key<br>  const secretKey = await crypto.subtle.importKey(&#39;pkcs8&#39;, keyArrayBuffer, encryptAlgorithm, true, [&#39;decrypt&#39;]);<br>  // decrypt the text with the public key<br>  const decryptedBuffer = await crypto.subtle.decrypt({<br>    name: &#39;RSA-OAEP&#39;,<br>  }, secretKey, fileArrayBuffer);<br><br>  return decryptedBuffer;<br>}<br><br><br>export const decryptStringRsa = async (str: string, pemString: string) =&gt; {<br>  // convert base64 encoded input string into ArrayBuffer<br>  const encodedPlaintext = _base64StringToArrayBuffer(str);<br>  const decrypted = await decryptRsa(encodedPlaintext, pemString);<br>  // decode the decrypted ArrayBuffer output<br>  const uint8Array = new Uint8Array(decrypted);<br>  const textDecoder = new TextDecoder();<br>  const decodedString = textDecoder.decode(uint8Array);<br>  return decodedString;<br>};</pre><h3>Hope you enjoyed the content !</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e7987bd43ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JS] How to use Web Crypto API in frontend — AES-256 File encryption (With openSSL equivalent)]]></title>
            <link>https://medium.com/@yinte1222/js-how-to-use-web-crypto-api-in-frontend-aes-256-file-encryption-with-openssl-equivalent-60abc7180b8a?source=rss-92699a3f0a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/60abc7180b8a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[openssl]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Yin Te Lan]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 07:25:10 GMT</pubDate>
            <atom:updated>2023-10-17T08:07:03.825Z</atom:updated>
            <content:encoded><![CDATA[<h3>[JavaScript] How to use Web Crypto API in web frontend — AES-256 File encryption (With openSSL command equivalent)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akYMTtkNZ5qnULkDQ3x_rQ.png" /></figure><p>In this project, I will show you how to use the Web Crypto API* to encrypt a file. Furtheremore, I will give some simple explain to it and provide the equivalent openSSL command to it.</p><p>Web Crypto API:</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API">https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API</a>.</p><p>The source code and demo is provided:</p><ul><li>Source Code:</li></ul><p><a href="https://github.com/benjamin5252/web_crypto_api_example">GitHub - benjamin5252/web_crypto_api_example: The example code to show how to use web crypto api in a react app</a></p><ul><li>Demo:</li></ul><p><a href="https://benjamin5252.github.io/web_crypto_api_example/">Encryption Tool</a></p><p>In the sorce code, the AES-256 file encryption code is in utils/AES_encryption.ts</p><h3><strong>1. Prepare an AES 256 key from passphrase</strong></h3><p>According to the definition, AES 256 require a 256 bit key. In this project, a 256 bit key is generated with sha-256 from user defined passphrase, and export it as hexadecimal string.</p><p>A IV value of the AES256 algorithm needs to be 128-bit long. In this project, a half of a key is exectly 256-bit long, so a half of the key is used as IV.</p><pre><br>// utils/AES_encryption.ts<br>const _stringToArrayBuffer = (str: string)=&gt;{<br>  const encoder = new TextEncoder();<br>  return encoder.encode(str).buffer;<br>}<br><br>const _digestMessage = async (message: string) =&gt; {<br>  const data = _stringToArrayBuffer(message);<br>  const hash = await crypto.subtle.digest(&quot;SHA-256&quot;, data);<br>  return hash;<br>}<br><br>const _arrayBufferToHexString = (buffer: ArrayBuffer) =&gt; {<br>  const byteArray = new Uint8Array(buffer);<br>  const hexCodes = [...byteArray].map(value =&gt; {<br>      const hexCode = value.toString(16);<br>      const paddedHexCode = hexCode.padStart(2, &#39;0&#39;);<br>      return paddedHexCode;<br>  });<br><br>  return hexCodes.join(&#39;&#39;);<br>}<br><br>export const getKeyFromPassphrase = async (passphrase: string) =&gt; {<br>  const key = await _digestMessage(passphrase);<br>  const keyHex = _arrayBufferToHexString(key);<br>  return keyHex<br>}<br><br>export const getIvFromPassphrase = async (passphrase: string) =&gt; {<br>  const keyHex = await getKeyFromPassphrase(passphrase); <br>  const ivHex = keyHex.substring(0, 32)<br>  return ivHex<br>}</pre><p>To utilize the Web Crypto API, a crypto object is used. It provides the digest funtion to give several hash methods. The sha-256 is used in this project.</p><p>The Web Crypto API takes and returns data in ArrayBuffer in most of the functions in it. Therefore, we have to deal with it in proper way.</p><h3>2. Encrypt file with AES-256</h3><p>As said, Web Crypto API takes ArrayBuffer as data input. In the Frontend, the file should be loaded as ArrayBuffer in the following code in page component.</p><pre>// pages/AesFileEncryptPage.tsx <br> <br>const encryptAes256 = () =&gt; {<br>  if (inputFile &amp;&amp; (passphrase || is256BitHex(aesKey))) {<br>    const reader = new FileReader();<br>    reader.onload = async function () {<br>      try{<br>        const encrypted = await encryptAes(<br>          reader.result as ArrayBuffer,<br>          aesKey,<br>          aesIv<br>        );<br>        saveOrOpenBlob(new Blob([encrypted]), inputFile.name || &quot;encrypted&quot;);<br>      }catch(err){<br>        alert(&#39;Encryption failed&#39;)<br>      }<br>      <br>    };<br>    reader.readAsArrayBuffer(inputFile);<br>  }<br>};<br><br>const saveOrOpenBlob = (blob, fileName) =&gt; {<br>  const tempEl = document.createElement(&quot;a&quot;);<br>  document.body.appendChild(tempEl);<br>  const url = window.URL.createObjectURL(blob);<br>  tempEl.href = url;<br>  tempEl.download = fileName;<br>  tempEl.click();<br>  window.URL.revokeObjectURL(url);<br>};</pre><p>Pass the file ArrayBuffer, key and iv into encryptAES().</p><pre>// utils/AES_encryption.ts<br><br>const _arrayBufferFromHexString = (hexString: string) =&gt; {<br>  const bytes = Uint8Array.from(hexString.match(/.{1,2}/g).map((byte: any) =&gt; parseInt(byte, 16)));<br>  return bytes.buffer;<br>}<br><br>export const encryptAes = async (fileArrayBuffer: ArrayBuffer, keyHex: string, ivHex: string) =&gt; {<br>  // decode the hex-encoded key and IV<br>  const ivArrayBuffer = _arrayBufferFromHexString(ivHex);<br>  const keyArrayBuffer = _arrayBufferFromHexString(keyHex);<br><br>  // prepare the secret key for encryption<br>  const secretKey = await crypto.subtle.importKey(&#39;raw&#39;, keyArrayBuffer, {<br>      name: &#39;AES-CBC&#39;,<br>      length: 256<br>  }, true, [&#39;encrypt&#39;, &#39;decrypt&#39;]);<br><br>  // encrypt the data with the secret key<br>  const ciphertextArrayBuffer = await crypto.subtle.encrypt({<br>      name: &#39;AES-CBC&#39;,<br>      iv: ivArrayBuffer<br>  }, secretKey, fileArrayBuffer);<br><br>  return ciphertextArrayBuffer<br>}</pre><p>AES-CBC is used in this project. There are some other kind of AES can be used, like AES-CTR, AES-GCM and AES-CBC*.</p><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt">https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt</a></li></ul><p>The crypto.subtle.importKey() is used to prepare the key object used in web crypto api. Then, crypto.subtle.encrypt() is used to encrypt the data. After that, you can get an encrypted data ArrayBuffer for download or other usage.</p><h3>3. Decrypt file with AES-256</h3><p>Read in the file as ArrayBuffer in page.</p><pre>// pages/AesFileEncryptPage.tsx<br>const decryptAes256 = () =&gt; {<br>  if (inputFile &amp;&amp; (passphrase || is256BitHex(aesKey))) {<br>    const reader = new FileReader();<br>    reader.onload = async function () {<br>      try{<br>        const decrypted = await decryptAes(<br>          reader.result as ArrayBuffer,<br>          aesKey,<br>          aesIv<br>        );<br>        console.log(decrypted);<br>        saveOrOpenBlob(new Blob([decrypted]), inputFile.name || decrypted);<br>      }catch(err){<br>        alert(&#39;Decryption failed&#39;)<br>      }<br>     <br>    };<br>    reader.readAsArrayBuffer(inputFile);<br>  }<br>};<br><br>const saveOrOpenBlob = (blob, fileName) =&gt; {<br>  const tempEl = document.createElement(&quot;a&quot;);<br>  document.body.appendChild(tempEl);<br>  const url = window.URL.createObjectURL(blob);<br>  tempEl.href = url;<br>  tempEl.download = fileName;<br>  tempEl.click();<br>  window.URL.revokeObjectURL(url);<br>};</pre><p>Pass the data ArrayBuffer into decryptAes()</p><pre>export const decryptAes = async (fileArrayBuffer: ArrayBuffer, keyHex: string, ivHex: string) =&gt; {<br>  // decode the hex-encoded key and IV<br>  const ivArrayBuffer = _arrayBufferFromHexString(ivHex);<br>  const keyArrayBuffer = _arrayBufferFromHexString(keyHex);<br><br>  // prepare the secret key for encryption<br>  const secretKey = await crypto.subtle.importKey(&#39;raw&#39;, keyArrayBuffer, {<br>    name: &#39;AES-CBC&#39;,<br>    length: 256<br>}, true, [&#39;encrypt&#39;, &#39;decrypt&#39;]);<br><br>  // decrypt the ciphertext with the secret key<br>  const decryptedBuffer = await crypto.subtle.decrypt({<br>      name: &#39;AES-CBC&#39;,<br>      iv: ivArrayBuffer<br>  }, secretKey, fileArrayBuffer);<br><br>  // return the decrypted data as an ArrayBuffer<br>  return decryptedBuffer;<br>}</pre><p>Remember to convert the input data including file, key and iv into ArrayBuffer before using the Web Crypto API just like the encryption part. crypto.subtle.decrypt() is used to decrypt data.</p><p>An decrypted data in ArrayBuffer is returned for furthere usage.</p><h3>4. openSSL equivalent</h3><p>I have tested that the openSSL commands bellow can decrypt the file encrypted with the Web Crypto API methods provided in this project and vice versa.</p><p>Encrypt:</p><pre>openssl enc -aes-256-cbc -nosalt -e -in &lt;input file name&gt; -out &lt;output file name&gt; -K &lt;key in Hex&gt; -iv &lt;iv in Hex&gt;</pre><p>Decrypt:</p><pre>openssl enc -aes-256-cbc -nosalt -d -in &lt;input file name&gt; -out &lt;output file name&gt; -K &lt;key in hex&gt; -iv &lt;iv in hex&gt;</pre><p>Reference:</p><ul><li><a href="https://medium.com/@tony.infisical/guide-to-web-crypto-api-for-encryption-decryption-1a2c698ebc25">Guide to Web Crypto API for encryption/decryption</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API">Web Crypto API - Web APIs | MDN</a></li></ul><h3>Hope you enjoy the content !</h3><h3>I will be very happy if you give me some claps.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60abc7180b8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[LeetCode JavasScript] How to use ‘constructor’ as an object key]]></title>
            <link>https://medium.com/@yinte1222/leetcode-javasscript-how-to-use-constructor-as-an-object-key-c0d42af4e508?source=rss-92699a3f0a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0d42af4e508</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototype-chain]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[Yin Te Lan]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 07:28:02 GMT</pubDate>
            <atom:updated>2023-09-05T07:29:52.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*oS8SUdBDjduSfYWawjB2WA.png" /><figcaption>The ‘constructor’ key of an object is ocupied by Object.prototype.constructor Object.</figcaption></figure><p>While solving the leetcode 290. word pattern, I found that the test case includes ‘constructor’ in the test case like the picture below. And my code failed due to the test case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDrQik00rHf3lezRjN4Qdw.png" /></figure><p>If I console.log out the constructor of the object I got the following, which is not the ‘undefined’ which I expected.</p><pre>let map = {}<br>console.log(map.constructor)<br>// output<br>// ƒ Object() { [native code] }</pre><h3>Cause</h3><p>This as caused by the prototype chain of Object. The object inherit the ‘constructor’ property from Object.prototype. The equivalent of the initiation of the Object is shown below.</p><pre>const map = Object.create(Object.prototype)<br>// equivalent to <br>// const map = {}</pre><h3>Solution</h3><p>Create the object without inherit the prototype from Object.prototype.</p><pre>const map =  Object.create(null)<br>console.log(map.constructor)<br>// output<br>// undefined</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0d42af4e508" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Nextjs Tutorial] How To Run A Next.js App In Docker Container]]></title>
            <link>https://medium.com/@yinte1222/nextjs-tutorial-how-to-run-a-next-js-app-in-docker-container-50ace42fc96b?source=rss-92699a3f0a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ace42fc96b</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[next]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Yin Te Lan]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 07:39:04 GMT</pubDate>
            <atom:updated>2023-03-23T07:39:04.910Z</atom:updated>
            <content:encoded><![CDATA[<p>The project shows you how to make Nextjs app work with Docker.</p><p>Source code:</p><p><a href="https://github.com/benjamin5252/nextjs-docker-starter">https://github.com/benjamin5252/nextjs-docker-starter</a></p><h3>Dependencies:</h3><ul><li>Docker</li><li>docker-compose</li></ul><p>The docker installation instruction can be found on the docs of Docker</p><p><a href="https://docs.docker.com/">https://docs.docker.com/</a></p><ul><li>node</li><li>npm</li></ul><h3>Create a Nextjs app</h3><p>As the instruction on</p><p><a href="https://nextjs.org/docs/getting-started">https://nextjs.org/docs/getting-started</a></p><pre>npx create-next-app@latest<br># or<br>yarn create next-app<br># or<br>pnpm create next-app</pre><h3>Add needed files for docker-compose</h3><ul><li>Dockerfile</li><li>docker-compose.yml</li><li>.dockerignore</li><li>.env</li></ul><p>Like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*1gHxc1RQditWC2yGL01QTg.png" /></figure><h3>Edit files</h3><ul><li><strong>Dockerfile</strong></li></ul><p>The Dockerfile is edited like below. The code in it will be explained line by line later.</p><p>— Whole file of “Dockerfile”:</p><pre>FROM node:18.15<br>RUN mkdir -p /usr/src/nextjs-app<br>WORKDIR /usr/src/nextjs-app<br>COPY . .<br>RUN npm i<br>RUN npm cache clean --force<br>RUN npm run build<br><br>EXPOSE 3000 <br><br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><ol><li>Build the image from node:&lt;version&gt; image (You can choose your node version for building the app)</li></ol><pre>FROM node:18.15</pre><p>2. Run the command in the docker container to create the working dir</p><pre>RUN mkdir -p /usr/src/nextjs-app</pre><p>3. Make the image to set the working dir</p><pre>WORKDIR /usr/src/nextjs-app</pre><p>4. Copy the files of the Nextjs project into the docker container. The path on the left means the dir outside of the docker. The dir on the means the dir in the docker container.</p><pre>COPY . .</pre><p>5. Flowing three commands are done in the docker container as the standard build script of the Nextjs app.</p><pre>RUN npm i<br>RUN npm cache clean --force<br>RUN npm run build</pre><p>6. Expose the port of the docker container to the outside</p><pre>EXPOSE 3000</pre><p>7. Run the start script after the build to run the Next app. (This command will be executed whenever the container is up, not only in the build stage.)</p><pre>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><ul><li><strong>docker-compose.yml</strong></li></ul><p>The docker-compose.yml should be edited like below, and the code will be explained later.</p><p>— Whole file of “docker-compose.yml”:</p><pre>version: &#39;3.5&#39;<br><br>services:<br>  nextjs:<br>    build:<br>      context: .<br>    image: nextjs-app<br>    container_name: nextjs-app<br>    ports:<br>      - ${OUTPUT_PORT}:3000<br><br># Remember to see the pages on port OUTPUT_PORT in .env</pre><ol><li>Define the version number of the docker-compose.yml format. You should config it according to your docker environment. The chart of the supported docker-compose.yml version and docker-engine version can be found below.</li></ol><p><a href="https://docs.docker.com/compose/compose-file/compose-versioning/">https://docs.docker.com/compose/compose-file/compose-versioning/</a></p><pre>version: &#39;3.5&#39;</pre><p>2. Define the services of your app, your can specify your desired services name to your docker-compose work. This can be not only one services.</p><pre>services:<br>  services_1:<br>    ...<br>  services_2:<br>    ...<br>  services_3:<br>    ...</pre><p>3. The build config of the docker image. Config the build work of the image, in this project the build is done in the current directory with path “.” in the “context:” option in the “build:”. It will find the Dockerfile in the directory to do the build job.</p><pre>build:<br>  context: .<br>    ...</pre><p>4. Define the output image name of the previous build job.</p><pre>image: &lt;image name&gt;</pre><p>5. Define the container name.</p><pre>container_name: &lt;container name&gt;</pre><p>6. Define the port mapping from outside to inside of the container.</p><pre>ports:<br>      - &lt;PORT OUTSIDE&gt;:&lt;PORT INSIDE&gt;<br>      - 8080:3000<br>        ...</pre><p>7. The docker-compose can take the variables from “.env” file in the directory with the code below</p><pre>${VARIABLE_NAME}</pre><p>The port mapping of this project is equal to the code below if the variable is not taken from .env.</p><p>These two are equal in this project:</p><pre>ports:<br>  - ${OUTPUT_PORT}:3000</pre><pre>ports:<br>  - 8080:3000<br><br># ${OUTPUT_PORT}=8080 in the .env</pre><ul><li><strong>.env</strong></li></ul><p>You can keep some variables of the docker-compose.yml in the “.env” file.</p><p>— Whole file of “.env”:</p><pre>OUTPUT_PORT=8080</pre><ul><li><strong>.dockerignore</strong></li></ul><p>Config the file you don’t want to copy to the docker container</p><p>— Whole file of “.dockerignore”</p><pre>node_modules</pre><h3>Build and run the container</h3><p>The container can be run with the following command.</p><pre>docker-compose up --build</pre><p>Then you can see the Nextjs app running on the “http://localhost:8080”</p><pre>http://localhost:8080</pre><p>The port number 8080 is from the OUTPUT_PORT of .env file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ace42fc96b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Nuxt3 Tutorial] How to run Nuxt 3 app in Docker]]></title>
            <link>https://medium.com/@yinte1222/nuxt-3-tutorial-how-to-run-nuxt-3-app-in-docker-with-dockerfile-and-docker-compose-yml-3400b6796b10?source=rss-92699a3f0a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3400b6796b10</guid>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Yin Te Lan]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 06:10:00 GMT</pubDate>
            <atom:updated>2023-03-22T06:15:02.288Z</atom:updated>
            <content:encoded><![CDATA[<p>The project shows you how to make Nuxt 3 app work with Docker.</p><p>Source code:</p><p><a href="https://github.com/benjamin5252/nuxt3-docker-starter">GitHub - benjamin5252/nuxt3-docker-starter: A minimal starter of Nuxt 3 app with docker</a></p><h3>Dependencies:</h3><ul><li>Docker</li><li>docker-compose</li></ul><p>The docker installation instruction can be found on the docs of Docker</p><p><a href="https://docs.docker.com/">https://docs.docker.com/</a></p><ul><li>node</li><li>npm</li></ul><h3>Create a nuxt app</h3><p>As the instruction on</p><p><a href="https://nuxt.com/">https://nuxt.com/</a></p><pre>npx nuxi@latest init &lt;project name&gt;</pre><h3>Add needed files for docker-compose</h3><ul><li>Dockerfile</li><li>docker-compose.yml</li><li>.dockerignore</li><li>.env</li></ul><p>Like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*kfrFYVaC5BgCHwCDK7djVg.png" /></figure><h3>Edit files</h3><ul><li><strong>package.json</strong></li></ul><p>Make sure there are scripts supporting “nuxt build” and “nuxt start“ for npm run.</p><p>— Whole file of “package.json”:</p><pre>{<br>  &quot;private&quot;: true,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;nuxt build&quot;,<br>    &quot;dev&quot;: &quot;nuxt dev&quot;,<br>    &quot;start&quot;: &quot;nuxt start&quot;,<br>    &quot;generate&quot;: &quot;nuxt generate&quot;,<br>    &quot;preview&quot;: &quot;nuxt preview&quot;,<br>    &quot;postinstall&quot;: &quot;nuxt prepare&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;nuxt&quot;: &quot;^3.3.1&quot;<br>  }<br>}</pre><ul><li><strong>Dockerfile</strong></li></ul><p>The Dockerfile is edited like below. The code in it will be explained line by line later.</p><p>— Whole file of “Dockerfile”:</p><pre>FROM node:18.15<br>RUN mkdir -p /usr/src/nuxt-app<br>WORKDIR /usr/src/nuxt-app<br>COPY . .<br>RUN npm i<br>RUN npm cache clean --force<br>RUN npm run build<br><br>EXPOSE 3000 <br><br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><ol><li>Build the image from node:&lt;version&gt; image (You can choose your node version for building the app)</li></ol><pre>FROM node:18.15</pre><p>2. Run the command in the docker container to create the working dir</p><pre>RUN mkdir -p /usr/src/nuxt-app</pre><p>3. Make the image to set the working dir</p><pre>WORKDIR /usr/src/nuxt-app</pre><p>4. Copy the files of the nuxt project into the docker container. The path on the left means the dir outside of the docker. The dir on the means the dir in the docker container.</p><pre>COPY . .</pre><p>5. Flowing three commands are done in the docker container as the standard build script of the Nuxt app.</p><pre>RUN npm i<br>RUN npm cache clean --force<br>RUN npm run build</pre><p>6. Expose the port of the docker container to the outside</p><pre>EXPOSE 3000 </pre><p>7. Run the start script after the build to run the nuxt app. (This command will be executed whenever the container is up, not only in the build stage.)</p><pre>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><ul><li><strong>docker-compose.yml</strong></li></ul><p>The docker-compose.yml should be edited like below, and the code will be explained later.</p><p>— Whole file of “docker-compose.yml”:</p><pre>version: &#39;3.5&#39;<br><br>services:<br>  nuxt:<br>    build:<br>      context: .<br>    image: nuxt-app<br>    container_name: nuxt-app<br>    ports:<br>      - ${OUTPUT_PORT}:3000<br><br># Remember to see the pages on port OUTPUT_PORT in .env</pre><ol><li>Define the version number of the docker-compose.yml format. You should config it according to your docker environment. The chart of the supported docker-compose.yml version and docker-engine version can be found below.</li></ol><p><a href="https://docs.docker.com/compose/compose-file/compose-versioning/"></a></p><pre>version: &#39;3.5&#39;</pre><ol><li>Define the services of your app, your can specify your desired services name to your docker-compose work. This can be not only one services.</li></ol><pre>services:<br>  services_1:<br>    ...<br>  services_2:<br>    ...<br>  services_3:<br>    ...</pre><p>2. The build config of the docker image. Config the build work of the image, in this project the build is done in the current directory with path “.” in the “context:” option in the “build:”. It will find the Dockerfile in the directory to do the build job.</p><pre>build:<br>  context: .<br>    ...</pre><p>3. Define the output image name of the previous build job.</p><pre>image: &lt;image name&gt;</pre><p>4. Define the container name.</p><pre>container_name: &lt;container name&gt;</pre><p>5. Define the port mapping from outside to inside of the container.</p><pre>ports:<br>      - &lt;PORT OUTSIDE&gt;:&lt;PORT INSIDE&gt;<br>      - 8080:3000<br>        ...</pre><p>6. The docker-compose can take the variables from “.env” file in the directory with the code below</p><pre>${VARIABLE_NAME}</pre><p>The port mapping of this project is equal to the code below if the variable is not taken from .env.</p><pre>ports:<br>  - 8080:3000<br><br># ${OUTPUT_PORT}=8080 in the .env </pre><ul><li><strong>.env</strong></li></ul><p>You can keep some variables of the docker-compose.yml in the “.env” file.</p><p>— Whole file of “.env”:</p><pre>OUTPUT_PORT=8080</pre><ul><li><strong>.dockerignore</strong></li></ul><p>Config the file you don’t want to copy to the docker container</p><p>— Whole file of “.dockerignore”</p><pre>node_modules<br>.nuxt<br>.output</pre><h3>Build and run the container</h3><p>The container can be run with the following command.</p><pre>docker-compose up --build</pre><p>Then you can see the Nuxt app run on the “http://localhost:8080”</p><pre>http://localhost:8080  </pre><p>The port number 8080 is from the OUTPUT_PORT of .env file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3400b6796b10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Nuxt3 Tutorial] How to perform coco-ssd object detection powered by tensorflow.js in a Nuxt 3 app.]]></title>
            <link>https://medium.com/@yinte1222/nuxt3-tutorial-how-to-perform-coco-ssd-object-detection-powered-by-tensorflow-js-in-a-nuxt-3-app-6e505323481?source=rss-92699a3f0a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e505323481</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[tensorflowjs]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <dc:creator><![CDATA[Yin Te Lan]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 05:36:58 GMT</pubDate>
            <atom:updated>2023-02-24T05:36:58.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZFs3G4HSpTOsRWh7gIeRg.png" /></figure><h3>Intro</h3><p>In this project, a simple example of using the pre-trained object detection model (coco-ssd) powered by tensorflow.js in a Nuxt 3 app is built.</p><p>Github Repo of the source code of this project:</p><p><a href="https://github.com/benjamin5252/tfjs-object-detection-nuxt3-example">https://github.com/benjamin5252/tfjs-object-detection-nuxt3-example</a></p><h3>Create Nuxt app</h3><p>Create one Nuxt 3 app according to the Installation instruction reference down below.</p><p>Reference:</p><p><a href="https://nuxt.com/docs/getting-started/installation">Installation</a></p><h3>Install dependencies</h3><p>Reference:</p><p><a href="https://github.com/tensorflow/tfjs-models/tree/master/coco-ssd">https://github.com/tensorflow/tfjs-models/tree/master/coco-ssd</a></p><p>According to the GitHub repo of the coco-ssd object detection pre-trained model, we have to install the following dependency “@tensorflow/tfjs-backend-cpu”, “@tensorflow/tfjs-backend-webgl”, and “@tensorflow-models/coco-ssd”. I found the latest version of “@tensorflow-models/coco-ssd” is not compatible with the latest version of the other two dependencies. The package.json is listed below. We can edited the package.json like below and perform “npm install”.</p><h4>package.json</h4><pre><br>{<br>  &quot;private&quot;: true,<br>  &quot;scripts&quot;: {<br>    &quot;build&quot;: &quot;nuxt build&quot;,<br>    &quot;dev&quot;: &quot;nuxt dev&quot;,<br>    &quot;generate&quot;: &quot;nuxt generate&quot;,<br>    &quot;preview&quot;: &quot;nuxt preview&quot;,<br>    &quot;postinstall&quot;: &quot;nuxt prepare&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;nuxt&quot;: &quot;^3.2.0&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@tensorflow-models/coco-ssd&quot;: &quot;^2.2.2&quot;,<br>    &quot;@tensorflow/tfjs-backend-cpu&quot;: &quot;^3.21.0&quot;,<br>    &quot;@tensorflow/tfjs-backend-webgl&quot;: &quot;^3.21.0&quot;<br>  }<br>}</pre><p>After editing the package.json perform the following command to install the dependencies</p><pre>npm install</pre><p>Replace the &lt;NuxtWelcome /&gt; in “app.vue” with “&lt;NuxtPage /&gt;” like below.</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;NuxtPage /&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Make a “pages” folder in our project and put “index.vue” for our main page. Then the nuxt app is setup for our project. The following part of the project will performed on this “index.vue” page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*o7sNlBd1YTMzAku1_1NT9Q.png" /></figure><h3>Use tensorflow.js coco-ssd object detection in the Nuxt app</h3><p>Add some UI to read images and a canvas to show the detection result in index.vue page. (I added the code in my “index.vue” page)</p><p>index.vue</p><pre><br>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div v-if=&quot;isLoadingModel&quot;&gt;Loading Model ...&lt;/div&gt;<br>        &lt;div v-else&gt;<br>            &lt;label for=&quot;avatar&quot;&gt;Choose a picture:&lt;/label&gt;<br>            &lt;input @change=&quot;getChange($event)&quot; type=&quot;file&quot; id=&quot;avatar&quot; name=&quot;avatar&quot; accept=&quot;image/*&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;img id=&quot;img_to_detect&quot;&gt;<br>        &lt;canvas id=&quot;detect_result&quot;&gt;&lt;/canvas&gt;<br><br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>&lt;/script&gt;<br>&lt;style&gt;<br>&lt;/style&gt;</pre><p>Import the modules with the code below in the top part of your Vue component &lt;script setup&gt; section.</p><pre><br>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div v-if=&quot;isLoadingModel&quot;&gt;Loading Model ...&lt;/div&gt;<br>        &lt;div v-else&gt;<br>            &lt;label for=&quot;avatar&quot;&gt;Choose a picture:&lt;/label&gt;<br>            &lt;input @change=&quot;getChange($event)&quot; type=&quot;file&quot; id=&quot;avatar&quot; name=&quot;avatar&quot; accept=&quot;image/*&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;img id=&quot;img_to_detect&quot;&gt;<br>        &lt;canvas id=&quot;detect_result&quot;&gt;&lt;/canvas&gt;<br><br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>  // import modules for object detection<br>  import &#39;@tensorflow/tfjs-backend-cpu&#39;<br>  import &#39;@tensorflow/tfjs-backend-webgl&#39;<br>  import * as cocoSsd from &#39;@tensorflow-models/coco-ssd&#39;<br><br>&lt;/script&gt;<br>&lt;style&gt;<br>&lt;/style&gt;</pre><p>Create some variables for page interaction and data store.</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div v-if=&quot;isLoadingModel&quot;&gt;Loading Model ...&lt;/div&gt;<br>        &lt;div v-else&gt;<br>            &lt;label for=&quot;avatar&quot;&gt;Choose a picture:&lt;/label&gt;<br>            &lt;input @change=&quot;getChange($event)&quot; type=&quot;file&quot; id=&quot;avatar&quot; name=&quot;avatar&quot; accept=&quot;image/*&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;img id=&quot;img_to_detect&quot;&gt;<br>        &lt;canvas id=&quot;detect_result&quot;&gt;&lt;/canvas&gt;<br><br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>  // import modules for object detection<br>  import &#39;@tensorflow/tfjs-backend-cpu&#39;<br>  import &#39;@tensorflow/tfjs-backend-webgl&#39;<br>  import * as cocoSsd from &#39;@tensorflow-models/coco-ssd&#39;<br>  <br>  const isLoadingModel = ref(false)<br>  let cocoSsdModel = null<br>&lt;/script&gt;<br>&lt;style&gt;<br>&lt;/style&gt;</pre><p>Load the ai model with “cocoSsd.load()” in the code beload when the page is mounted.</p><pre>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div v-if=&quot;isLoadingModel&quot;&gt;Loading Model ...&lt;/div&gt;<br>        &lt;div v-else&gt;<br>            &lt;label for=&quot;avatar&quot;&gt;Choose a picture:&lt;/label&gt;<br>            &lt;input @change=&quot;getChange($event)&quot; type=&quot;file&quot; id=&quot;avatar&quot; name=&quot;avatar&quot; accept=&quot;image/*&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;img id=&quot;img_to_detect&quot;&gt;<br>        &lt;canvas id=&quot;detect_result&quot;&gt;&lt;/canvas&gt;<br><br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script setup&gt;<br>  // import modules for object detection<br>  import &#39;@tensorflow/tfjs-backend-cpu&#39;<br>  import &#39;@tensorflow/tfjs-backend-webgl&#39;<br>  import * as cocoSsd from &#39;@tensorflow-models/coco-ssd&#39;<br><br>  const isLoadingModel = ref(false)<br>  let cocoSsdModel = null<br><br>  onMounted(async () =&gt; {<br>      isLoadingModel.value = true<br>      // Load the ai model<br>      cocoSsdModel = await cocoSsd.load()<br>      isLoadingModel.value = false<br>  })<br>&lt;/script&gt;<br>&lt;style&gt;<br>&lt;/style&gt;<br></pre><p>Get detection by passing the “img” element in to the “cocoSsdModel.detect(img)” function to get the detection result. The function to draw the detection result on to the canvas is show as “getDetect()” function below. And a “getChange()” is added to get the file input and pass the img to “getDetect(img)” after the img is loaded. The code is completed in this project down below.</p><p>index.vue (complete)</p><pre><br>&lt;template&gt;<br>    &lt;div&gt;<br>        &lt;div v-if=&quot;isLoadingModel&quot;&gt;Loading Model ...&lt;/div&gt;<br>        &lt;div v-else&gt;<br>            &lt;label for=&quot;avatar&quot;&gt;Choose a picture:&lt;/label&gt;<br>            &lt;input @change=&quot;getChange($event)&quot; type=&quot;file&quot; id=&quot;avatar&quot; name=&quot;avatar&quot; accept=&quot;image/*&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;img id=&quot;img_to_detect&quot;&gt;<br>        &lt;canvas id=&quot;detect_result&quot;&gt;&lt;/canvas&gt;<br><br>    &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>// import modules for object detection<br>import &#39;@tensorflow/tfjs-backend-cpu&#39;<br>import &#39;@tensorflow/tfjs-backend-webgl&#39;<br>import * as cocoSsd from &#39;@tensorflow-models/coco-ssd&#39;<br><br>const isLoadingModel = ref(false)<br>let cocoSsdModel = null<br><br>onMounted(async () =&gt; {<br>    isLoadingModel.value = true<br>    // Load the ai model<br>    cocoSsdModel = await cocoSsd.load()<br>    isLoadingModel.value = false<br>})<br><br>const getChange = (e) =&gt; {<br>    const url = URL.createObjectURL(e.target.files[0])<br>    const img = document.getElementById(&#39;img_to_detect&#39;)<br>    img.width = 300<br>    img.height = 300<br>    img.src = url<br>    let result = null;<br>    img.onload = async () =&gt; {<br>        result = await getDetect(img)<br>        <br>    }<br>}<br><br>const getDetect = async (img) =&gt; {<br>    // get detection result<br>    const result = await cocoSsdModel.detect(img)<br><br>    const canvas = document.getElementById(&#39;detect_result&#39;);<br>    const color=[&quot;red&quot;,&quot;green&quot;,&quot;blue&quot;]<br>    canvas.width=img.width ;<br>    canvas.height=img.height ;<br>    const context = canvas.getContext(&#39;2d&#39;);<br>    context.drawImage(img, 0, 0, img.width,img.height);<br>    context.font = &#39;40px Arial&#39;;<br>    <br>    for (let i = 0; i &lt; result.length; i++) {<br>        context.beginPath();<br>        context.rect(...result[i].bbox);<br>        context.lineWidth = 5;<br>        context.strokeStyle = color[i%3];<br>        context.fillStyle = color[i%3];<br>        context.stroke();<br>        context.fillText(<br>            result[i].score.toFixed(3) + &#39; &#39; + result[i].class, <br>            result[i].bbox[0],<br>            result[i].bbox[1] - 5);<br>    }<br>    return result<br>}<br>&lt;/script&gt;<br><br>&lt;style&gt;<br>&lt;/style&gt;</pre><h3>Result:</h3><p>Run the dev comment to show the outcome.</p><pre>npm run dev</pre><p>The web page interaction will be like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhdMv_UiKcSiCsfSgArUgQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e505323481" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Nuxt3] 如何在Nuxt中使用Web Worker]]></title>
            <link>https://medium.com/@yinte1222/nuxt3-%E5%A6%82%E4%BD%95%E5%9C%A8nuxt%E4%B8%AD%E4%BD%BF%E7%94%A8web-worker-d411e52d6b25?source=rss-92699a3f0a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d411e52d6b25</guid>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[web-workers-in-javascript]]></category>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <dc:creator><![CDATA[Yin Te Lan]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 10:39:22 GMT</pubDate>
            <atom:updated>2023-01-27T10:39:22.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*b2Z_vsOxy6XnDcST7GSMPQ.gif" /></figure><h3>前言：</h3><p>Nuxt是近期很流行的前端Vue SSR框架, 目前最新版本出到第三版，簡稱Nuxt3。而前端效能受限於原生Javascript的單執行緒弱點，在執行運算時無法兼顧畫面更新而造成畫面卡頓。但現在有了HTML Web Worker api可以進行多執行緒背景運算。本專案在Nuxt 3 app用兩個方法實作了web worker，並比較了效能。</p><h3><strong>建立 Nuxt 3 app</strong></h3><p><a href="https://nuxt.com/docs/getting-started/installation">Installation</a></p><p>根據Nuxt3的文件建立一個Nuxt app。第一步用下列指令建立專案資料夾。其中&lt;project-name&gt;要換成你想要的專案資料夾名稱。</p><pre>npx nuxi init &lt;project-name&gt;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VfdzopDFUKw6OvsjkxCyww.png" /></figure><p>用下列指令打開專案資料夾</p><pre>cd &lt;project-name&gt;</pre><p>在專案資料夾底下執行以下指令來安裝所需套件</p><pre>npm install</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2K2ViF2UTlP4ieFT7jYlA.png" /></figure><p>用Vscode 打開資料夾</p><ul><li>vscode:</li></ul><p><a href="https://code.visualstudio.com/">Visual Studio Code - Build what comes next</a></p><pre>code .</pre><p>資料夾結構如下所示：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*mAoC0Ch_h4Ln0H-TdzZFMQ.png" /></figure><p>修改“app.vue”如下</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;NuxtPage /&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSnDsJgIXQaHpyDLARzJrg.png" /></figure><p>在專案資料夾加入”pages”資料夾來裝所要生成的頁面，然後建立“index.vue”作為主頁。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*OdjALFzsDseCJn3MNlgu0g.png" /></figure><p>在index.vue中輸入以下程式，其中包含sumNumMainMainThread函式來在主執行緒中計算0+1+2+….+1000000000的值。</p><pre>&lt;!-- index.vue --&gt;<br>&lt;template lang=&quot;&quot;&gt;<br>    &lt;div&gt;<br>        &lt;button @click=&quot;cal(&#39;mainThread&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Main thread)&lt;/button&gt;<br>        &lt;div v-for=&quot;(val, index) in countingMsg&quot;&gt;{{val}}&lt;/div&gt;<br>        &lt;div class=&quot;css_animated_part&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script  setup &gt;<br>const numToSum = ref(1000000000)<br>const countingMsg = ref([])<br><br>const cal = async (type) =&gt; {<br>    let sum = 0;<br>    const start = performance.now();<br>    if (type === &#39;mainThread&#39;) {<br>        sum = await sumNumMainMainThread()<br>    } <br>    const end = performance.now();<br>    countingMsg.value.push(`The sum of 0 to ${numToSum.value} is  ${sum} (${type})  (time spent: ${end - start} ms)`)<br>}<br><br>// calculate answer on main thread<br>const sumNumMainMainThread = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        console.log(&#39;In main thread: calculating sum to &#39; + numToSum.value)<br>        let sum = 0;<br>        for (let i = 1; i &lt;= numToSum.value; i++) {<br>            sum += i;<br>        }<br>        console.log(&#39;In main thread: &#39; + &#39;The sum of 0 to &#39; + numToSum.value + &#39; is &#39; + sum)<br>        resolve(sum)<br>    })<br><br>}<br><br>&lt;/script&gt;<br>&lt;style lang=&quot;css&quot;&gt;<br>.css_animated_part {<br>    width: 100px;<br>    height: 100px;<br>    position: relative;<br>    background-color: red;<br>    animation-name: example;<br>    animation-duration: 4s;<br>    animation-iteration-count: infinite;<br>}<br><br>@keyframes example {<br>    0% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br><br>    25% {<br>        background-color: yellow;<br>        left: 200px;<br>        top: 0px;<br>    }<br><br>    50% {<br>        background-color: blue;<br>        left: 200px;<br>        top: 200px;<br>    }<br><br>    75% {<br>        background-color: green;<br>        left: 0px;<br>        top: 200px;<br>    }<br><br>    100% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br>}<br>&lt;/style&gt;</pre><p>執行以下指令來看我們目前的頁面</p><pre>npm run dev</pre><p>用瀏覽器開啟預設http://localhost:3000來看頁面長怎樣</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WztTAm6_AkHH89YC2UjHyw.png" /></figure><h3>在主執行序進行運算</h3><p>如以下gif,在主執行序進行運算的話會造成CSS動畫卡頓無法更新頁面。這就是單執行緒的弱點。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*GysuT_YxBRU_5s7sq7I4CA.gif" /></figure><h3><strong>在public資料夾放web worker的程式</strong></h3><p>public資料夾可以放置所需靜態資源，所以web worker的程式也可以放置在此。</p><p>建立public資料夾，並建立worker.js。在worker.js中輸入以下程式。</p><pre>//worker.js<br>const countSum= (n)=&gt;{<br> let sum = 0;<br> for(let i =1; i &lt;= n; i++){<br>  sum += i;<br> }<br> return sum<br>} <br><br>self.addEventListener(&#39;message&#39;, function(e) {<br>  console.log(&quot;In worker (public): received data: &quot;+ e.data)<br>  let sum = countSum(e.data)<br>  let message = &#39;In worker (public): The sum of 1 to &#39; + e.data + &#39; is &#39; + sum<br>  console.log(message)<br>  self.postMessage(sum)<br>}, false);</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*be3xH3gOTWygH_xGOMOGrw.png" /></figure><p>要在pages/index.vue中使用web worker 需要在其中用“/&lt;path in public&gt;”來取得public/worker.js的資源。並用new Worker() api來建立worker.</p><pre>const worker = new Worker(&#39;/worker.js&#39;)</pre><p>修改後的pages/index.vue如下</p><pre>&lt;!-- index.vue --&gt;<br>&lt;template lang=&quot;&quot;&gt;<br>    &lt;div&gt;<br>        &lt;button @click=&quot;cal(&#39;mainThread&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Main thread)&lt;/button&gt;<br>        &lt;button @click=&quot;cal(&#39;workerPublic&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Worker Public)&lt;/button&gt;<br>        &lt;div v-for=&quot;(val, index) in countingMsg&quot;&gt;{{val}}&lt;/div&gt;<br>        &lt;div class=&quot;css_animated_part&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script  setup &gt;<br>const numToSum = ref(1000000000)<br>const countingMsg = ref([])<br><br>const cal = async (type) =&gt; {<br>    let sum = 0;<br>    const start = performance.now();<br>    if (type === &#39;mainThread&#39;) {<br>        sum = await sumNumMainMainThread()<br>    } else if (type === &#39;workerPublic&#39;) {<br>        sum = await sumNumWorkerPublic()<br>    } <br>    const end = performance.now();<br>    countingMsg.value.push(`The sum of 0 to ${numToSum.value} is  ${sum} (${type})  (time spent: ${end - start} ms)`)<br>}<br><br>// calculate answer on main thread<br>const sumNumMainMainThread = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        console.log(&#39;In main thread: calculating sum to &#39; + numToSum.value)<br>        let sum = 0;<br>        for (let i = 1; i &lt;= numToSum.value; i++) {<br>            sum += i;<br>        }<br>        console.log(&#39;In main thread: &#39; + &#39;The sum of 0 to &#39; + numToSum.value + &#39; is &#39; + sum)<br>        resolve(sum)<br>    })<br><br>}<br><br>// calculate the answer with web worker create from /public/worker.js<br>const sumNumWorkerPublic = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        const worker = new Worker(&#39;/worker.js&#39;)<br>        worker.postMessage(numToSum.value);<br>        worker.addEventListener(&#39;message&#39;, (e) =&gt; {<br>            if (e.data) {<br>                resolve(e.data)<br>                worker.terminate()<br>            }<br>        }, false);<br>    })<br>}<br><br>&lt;/script&gt;<br>&lt;style lang=&quot;css&quot;&gt;<br>.css_animated_part {<br>    width: 100px;<br>    height: 100px;<br>    position: relative;<br>    background-color: red;<br>    animation-name: example;<br>    animation-duration: 4s;<br>    animation-iteration-count: infinite;<br>}<br><br>@keyframes example {<br>    0% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br><br>    25% {<br>        background-color: yellow;<br>        left: 200px;<br>        top: 0px;<br>    }<br><br>    50% {<br>        background-color: blue;<br>        left: 200px;<br>        top: 200px;<br>    }<br><br>    75% {<br>        background-color: green;<br>        left: 0px;<br>        top: 200px;<br>    }<br><br>    100% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br>}<br>&lt;/style&gt;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*HixZJNXwMcCAdDzKmd5AaQ.gif" /></figure><h3>在任意非public路徑置放Worker script</h3><p>Nuxt 3 是基於Vite所以在使用資源路徑時需要用Vite的規則。而Vite文件中有針對Web Worker有說明用法。</p><p><a href="https://vitejs.dev/guide/features.html#web-workers">Vite</a></p><p>建立“/assets/workers/”路徑，並建立“workerVite.js”在裡面。在裡面加入以下程式。</p><pre>//workerVite.js<br>const countSum= (n)=&gt;{<br>    let sum = 0;<br>    for(let i =1; i &lt;= n; i++){<br>     sum += i;<br>    }<br>    return sum<br>   } <br>   <br>   self.addEventListener(&#39;message&#39;, function(e) {<br>     console.log(&quot;In worker (vite): received data: &quot;+ e.data)<br>     let sum = countSum(e.data)<br>     let message = &#39;In worker (vite): The sum of 1 to &#39; + e.data + &#39; is &#39; + sum<br>     console.log(message)<br>     self.postMessage(sum)<br>   }, false);</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9oydbWwMBmN-B5byxSHeQ.png" /></figure><p>修改index.vue來用這個worker script。</p><pre>&lt;!-- index.vue --&gt;<br>&lt;template lang=&quot;&quot;&gt;<br>    &lt;div&gt;<br>        &lt;button @click=&quot;cal(&#39;mainThread&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Main thread)&lt;/button&gt;<br>        &lt;button @click=&quot;cal(&#39;workerPublic&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Worker Public)&lt;/button&gt;<br>        &lt;button @click=&quot;cal(&#39;workerVite&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Worker Vite)&lt;/button&gt;<br>        &lt;div v-for=&quot;(val, index) in countingMsg&quot;&gt;{{val}}&lt;/div&gt;<br>        &lt;div class=&quot;css_animated_part&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script  setup &gt;<br>// import worker script according to the doc of Vite<br>import MyWorker from &#39;@/assets/workers/workerVite?worker&#39;<br>const numToSum = ref(1000000000)<br>const countingMsg = ref([])<br><br>const cal = async (type) =&gt; {<br>    let sum = 0;<br>    const start = performance.now();<br>    if (type === &#39;mainThread&#39;) {<br>        sum = await sumNumMainMainThread()<br>    } else if (type === &#39;workerPublic&#39;) {<br>        sum = await sumNumWorkerPublic()<br>    } else if (type === &#39;workerVite&#39;) {<br>        sum = await sumNumWorkerVite()<br>    }<br>    const end = performance.now();<br>    countingMsg.value.push(`The sum of 0 to ${numToSum.value} is  ${sum} (${type})  (time spent: ${end - start} ms)`)<br>}<br><br>// calculate answer on main thread<br>const sumNumMainMainThread = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        console.log(&#39;In main thread: calculating sum to &#39; + numToSum.value)<br>        let sum = 0;<br>        for (let i = 1; i &lt;= numToSum.value; i++) {<br>            sum += i;<br>        }<br>        console.log(&#39;In main thread: &#39; + &#39;The sum of 0 to &#39; + numToSum.value + &#39; is &#39; + sum)<br>        resolve(sum)<br>    })<br><br>}<br><br>// calculate the answer with web worker create from /public/worker.js<br>const sumNumWorkerPublic = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        const worker = new Worker(&#39;/worker.js&#39;)<br>        worker.postMessage(numToSum.value);<br>        worker.addEventListener(&#39;message&#39;, (e) =&gt; {<br>            if (e.data) {<br>                resolve(e.data)<br>                worker.terminate()<br>            }<br>        }, false);<br>    })<br>}<br><br>// calculate the answer with web worker create from /assets/workers/worker.js<br>const sumNumWorkerVite = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        const worker = new MyWorker()<br>        worker.postMessage(numToSum.value);<br>        worker.addEventListener(&#39;message&#39;, (e) =&gt; {<br>            if (e.data) {<br>                resolve(e.data)<br>                worker.terminate()<br>            }<br>        }, false);<br>    })<br>}<br><br>&lt;/script&gt;<br>&lt;style lang=&quot;css&quot;&gt;<br>.css_animated_part {<br>    width: 100px;<br>    height: 100px;<br>    position: relative;<br>    background-color: red;<br>    animation-name: example;<br>    animation-duration: 4s;<br>    animation-iteration-count: infinite;<br>}<br><br>@keyframes example {<br>    0% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br><br>    25% {<br>        background-color: yellow;<br>        left: 200px;<br>        top: 0px;<br>    }<br><br>    50% {<br>        background-color: blue;<br>        left: 200px;<br>        top: 200px;<br>    }<br><br>    75% {<br>        background-color: green;<br>        left: 0px;<br>        top: 200px;<br>    }<br><br>    100% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br>}<br>&lt;/style&gt;</pre><p>可以注意import的部分，根據Vite文件我們要用以下程式來import worker script</p><pre>import MyWorker from &#39;@/assets/workers/workerVite?worker&#39;</pre><p>建立worker要用以下指令</p><pre>const worker = new MyWorker()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*slMiH-CFHq3s3_LmEY5mnw.gif" /></figure><h3>性能比較</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*b2Z_vsOxy6XnDcST7GSMPQ.gif" /></figure><p>可以明顯看到不管是用哪種方法建立Web Worker，用web worker進行計算皆不會像在主執行序進行運算一樣影響畫面顯示性能。並且兩種web worker性能並無區別，計算速度都一樣比主執行緒快7倍。</p><h3>原始碼：</h3><p><a href="https://github.com/benjamin5252/web-worker-nuxt3-example">https://github.com/benjamin5252/web-worker-nuxt3-example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d411e52d6b25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Nuxt3] How To Use Web Workers In A Nuxt App]]></title>
            <link>https://medium.com/@yinte1222/nuxt3-how-to-use-web-workers-in-a-nuxt-app-d03c1c8f2952?source=rss-92699a3f0a0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d03c1c8f2952</guid>
            <category><![CDATA[web-workers-in-javascript]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[nuxt-3]]></category>
            <dc:creator><![CDATA[Yin Te Lan]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 09:05:02 GMT</pubDate>
            <atom:updated>2023-01-30T12:33:32.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*b2Z_vsOxy6XnDcST7GSMPQ.gif" /></figure><h3>Intro</h3><p>This project is written to share the usage of Web Work in the Nuxt3 app. Web Work is a fantastic feature of modern front-end web development. Which can provide the possibility of multithread computing on the web frontend. The combination of Web Worker and the popular SSR framework Nuxt3 can provide unlimited possibilities.</p><h3>Create a nuxt3 app</h3><p><a href="https://nuxt.com/docs/getting-started/installation">Installation</a></p><p>Create a nuxt app with the command below in, the command line, terminal, PowerShell, bash, or any other shell interface (the PowerShell in windows is used in this project). The “&lt;project-name&gt;” command should be replaced with your project name (“web-worker-nuxt” is used as project name in this project). There will be one project directory created by nuxi.</p><pre>npx nuxi init &lt;project-name&gt;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VfdzopDFUKw6OvsjkxCyww.png" /></figure><p>Open the project directory with the command below</p><pre>cd &lt;project-name&gt;</pre><p>Install dependencies with npm install. There will be some deprecated modules used in the nuxt app. However, it is not a big problem. The mentainance team of nuxt is keeping an eye on the major changes of the dependencies regularly.</p><pre>npm install</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2K2ViF2UTlP4ieFT7jYlA.png" /></figure><p>Open the directory with *vscode with the command below in the project folder.</p><ul><li>vscode:</li></ul><p><a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a></p><pre>code .</pre><p>The stucture of the nuxt project will be something like the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*mAoC0Ch_h4Ln0H-TdzZFMQ.png" /></figure><p>Modify the code in “app.vue” to load our own pages in “/pages” folder</p><pre><br>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;NuxtPage /&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSnDsJgIXQaHpyDLARzJrg.png" /></figure><p>To make my own pages in the Nuxt app. Add a “pages” folder in the project directory. And add an “index.vue” in the “pages” folder like the structure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*OdjALFzsDseCJn3MNlgu0g.png" /></figure><p>Type the code below in the “pages/index.vue” for createing our first page. I designed a heavy calculation to sum 0 to 1000000000 with on page script which will be run on main thread for comparism to the worker we are going to use in the web app.</p><pre>&lt;!-- index.vue --&gt;<br>&lt;template lang=&quot;&quot;&gt;<br>    &lt;div&gt;<br>        &lt;button @click=&quot;cal(&#39;mainThread&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Main thread)&lt;/button&gt;<br>        &lt;div v-for=&quot;(val, index) in countingMsg&quot;&gt;{{val}}&lt;/div&gt;<br>        &lt;div class=&quot;css_animated_part&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script  setup &gt;<br>const numToSum = ref(1000000000)<br>const countingMsg = ref([])<br><br><br>const cal = async (type) =&gt; {<br>    let sum = 0;<br>    const start = performance.now();<br>    if (type === &#39;mainThread&#39;) {<br>        sum = await sumNumMainMainThread()<br>    } <br>    const end = performance.now();<br>    countingMsg.value.push(`The sum of 0 to ${numToSum.value} is  ${sum} (${type})  (time spent: ${end - start} ms)`)<br>}<br><br>// calculate answer on main thread<br>const sumNumMainMainThread = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        console.log(&#39;In main thread: calculating sum to &#39; + numToSum.value)<br>        let sum = 0;<br>        for (let i = 1; i &lt;= numToSum.value; i++) {<br>            sum += i;<br>        }<br>        console.log(&#39;In main thread: &#39; + &#39;The sum of 0 to &#39; + numToSum.value + &#39; is &#39; + sum)<br>        resolve(sum)<br>    })<br><br>}<br><br>&lt;/script&gt;<br>&lt;style lang=&quot;css&quot;&gt;<br>.css_animated_part {<br>    width: 100px;<br>    height: 100px;<br>    position: relative;<br>    background-color: red;<br>    animation-name: example;<br>    animation-duration: 4s;<br>    animation-iteration-count: infinite;<br>}<br><br>@keyframes example {<br>    0% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br><br>    25% {<br>        background-color: yellow;<br>        left: 200px;<br>        top: 0px;<br>    }<br><br>    50% {<br>        background-color: blue;<br>        left: 200px;<br>        top: 200px;<br>    }<br><br>    75% {<br>        background-color: green;<br>        left: 0px;<br>        top: 200px;<br>    }<br><br>    100% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br>}<br>&lt;/style&gt;</pre><p>Run the Nuxt dev command below in the project directory to see the preview of the web pages locally.</p><pre>npm run dev</pre><p>Type the default preview localhost URL below in your browser to see the nuxt page is running properly. And the console is opened with “F12” to see the log in this project. Then the Nuxt app is basically prepared for this project.</p><pre>http://localhost:3000</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WztTAm6_AkHH89YC2UjHyw.png" /></figure><h3>The calculation on the main thread</h3><p>As the output of the web page (shown in the gif below) created on the scrip in the index page. When some intensive calculation is executed on the main thread of the page, the page rendering including the CSS animation created in the page is stopped by the resource domination by the calculation. That is the weak point of the single thread nature of JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*GysuT_YxBRU_5s7sq7I4CA.gif" /></figure><h3>Create Web Workers from script hosted in “public” folder</h3><p>According to the <a href="https://www.w3schools.com/html/html5_webworkers.asp">https://www.w3schools.com/html/html5_webworkers.asp</a>, we have to find a place to statically host a “worker.js” containing the script we want to put in our web worker. In Nuxt3 the “public” folder is for users to host static files, so it is a valid place to put our “worker.js”.</p><p>Create “public” folder in our project and create one “worker.js” in the folder. And put the script below to calculate the sum into the “worker.js”.</p><pre>//worker.js<br>const countSum= (n)=&gt;{<br> let sum = 0;<br> for(let i =1; i &lt;= n; i++){<br>  sum += i;<br> }<br> return sum<br>} <br><br>self.addEventListener(&#39;message&#39;, function(e) {<br>  console.log(&quot;In worker (public): received data: &quot;+ e.data)<br>  let sum = countSum(e.data)<br>  let message = &#39;In worker (public): The sum of 1 to &#39; + e.data + &#39; is &#39; + sum<br>  console.log(message)<br>  self.postMessage(sum)<br>}, false);</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*be3xH3gOTWygH_xGOMOGrw.png" /></figure><p>To use the “worker.js” in our page, a path to “worker.js” should be declared. In Nuxt3, the contents in public folder can be access by path “/&lt;path in public&gt;” in nuxt pages . Hance, the worker can be new by the script below.</p><pre>const worker = new Worker(&#39;/worker.js&#39;)</pre><p>The “index.vue” can be modified like the below to use the worker to calculate the sum.</p><pre>&lt;!-- index.vue --&gt;<br>&lt;template lang=&quot;&quot;&gt;<br>    &lt;div&gt;<br>        &lt;button @click=&quot;cal(&#39;mainThread&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Main thread)&lt;/button&gt;<br>        &lt;button @click=&quot;cal(&#39;workerPublic&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Worker Public)&lt;/button&gt;<br>        &lt;div v-for=&quot;(val, index) in countingMsg&quot;&gt;{{val}}&lt;/div&gt;<br>        &lt;div class=&quot;css_animated_part&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script  setup &gt;<br>const numToSum = ref(1000000000)<br>const countingMsg = ref([])<br><br><br>const cal = async (type) =&gt; {<br>    let sum = 0;<br>    const start = performance.now();<br>    if (type === &#39;mainThread&#39;) {<br>        sum = await sumNumMainMainThread()<br>    } else if (type === &#39;workerPublic&#39;) {<br>        sum = await sumNumWorkerPublic()<br>    } <br>    const end = performance.now();<br>    countingMsg.value.push(`The sum of 0 to ${numToSum.value} is  ${sum} (${type})  (time spent: ${end - start} ms)`)<br>}<br><br>// calculate answer on main thread<br>const sumNumMainMainThread = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        console.log(&#39;In main thread: calculating sum to &#39; + numToSum.value)<br>        let sum = 0;<br>        for (let i = 1; i &lt;= numToSum.value; i++) {<br>            sum += i;<br>        }<br>        console.log(&#39;In main thread: &#39; + &#39;The sum of 0 to &#39; + numToSum.value + &#39; is &#39; + sum)<br>        resolve(sum)<br>    })<br><br>}<br><br><br>// calculate the answer with web worker create from /public/worker.js<br>const sumNumWorkerPublic = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        const worker = new Worker(&#39;/worker.js&#39;)<br>        worker.postMessage(numToSum.value);<br>        worker.addEventListener(&#39;message&#39;, (e) =&gt; {<br>            if (e.data) {<br>                resolve(e.data)<br>                worker.terminate()<br>            }<br>        }, false);<br>    })<br>}<br><br><br><br>&lt;/script&gt;<br>&lt;style lang=&quot;css&quot;&gt;<br>.css_animated_part {<br>    width: 100px;<br>    height: 100px;<br>    position: relative;<br>    background-color: red;<br>    animation-name: example;<br>    animation-duration: 4s;<br>    animation-iteration-count: infinite;<br>}<br><br>@keyframes example {<br>    0% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br><br>    25% {<br>        background-color: yellow;<br>        left: 200px;<br>        top: 0px;<br>    }<br><br>    50% {<br>        background-color: blue;<br>        left: 200px;<br>        top: 200px;<br>    }<br><br>    75% {<br>        background-color: green;<br>        left: 0px;<br>        top: 200px;<br>    }<br><br>    100% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br>}<br>&lt;/style&gt;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*HixZJNXwMcCAdDzKmd5AaQ.gif" /></figure><h3>Create Web Workers from scripts hosted in “assets” folder as compiled part in the project directory with Vite.</h3><p>The Nuxt 3 app is created with Vite, so the scripts host in the Nuxt3 app should follow the rule of Vite.</p><p>I followed the web worker part of the Vite Doc to create web workers in Nuxt3 app.</p><p><a href="https://vitejs.dev/guide/features.html#web-workers">https://vitejs.dev/guide/features.html#web-workers</a></p><p>Create path “/assets/workers/” and put “workerVite.js” in “/assets/workers/” and put the code below in the “workerVite.js”</p><pre>//workerVite.js<br>const countSum= (n)=&gt;{<br>    let sum = 0;<br>    for(let i =1; i &lt;= n; i++){<br>     sum += i;<br>    }<br>    return sum<br>   } <br>   <br>   self.addEventListener(&#39;message&#39;, function(e) {<br>     console.log(&quot;In worker (vite): received data: &quot;+ e.data)<br>     let sum = countSum(e.data)<br>     let message = &#39;In worker (vite): The sum of 1 to &#39; + e.data + &#39; is &#39; + sum<br>     console.log(message)<br>     self.postMessage(sum)<br>   }, false);</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z9oydbWwMBmN-B5byxSHeQ.png" /></figure><p>Put the code below in “index.vue” to use the worker.</p><pre>&lt;!-- index.vue --&gt;<br>&lt;template lang=&quot;&quot;&gt;<br>    &lt;div&gt;<br>        &lt;button @click=&quot;cal(&#39;mainThread&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Main thread)&lt;/button&gt;<br>        &lt;button @click=&quot;cal(&#39;workerPublic&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Worker Public)&lt;/button&gt;<br>        &lt;button @click=&quot;cal(&#39;workerVite&#39;)&quot;&gt;Sum 0 to {{ numToSum }} (Worker Vite)&lt;/button&gt;<br>        &lt;div v-for=&quot;(val, index) in countingMsg&quot;&gt;{{val}}&lt;/div&gt;<br>        &lt;div class=&quot;css_animated_part&quot;&gt;&lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script  setup &gt;<br>// import worker script according to the doc of Vite<br>import MyWorker from &#39;@/assets/workers/workerVite?worker&#39;<br>const numToSum = ref(1000000000)<br>const countingMsg = ref([])<br><br><br>const cal = async (type) =&gt; {<br>    let sum = 0;<br>    const start = performance.now();<br>    if (type === &#39;mainThread&#39;) {<br>        sum = await sumNumMainMainThread()<br>    } else if (type === &#39;workerPublic&#39;) {<br>        sum = await sumNumWorkerPublic()<br>    } else if (type === &#39;workerVite&#39;) {<br>        sum = await sumNumWorkerVite()<br>    }<br>    const end = performance.now();<br>    countingMsg.value.push(`The sum of 0 to ${numToSum.value} is  ${sum} (${type})  (time spent: ${end - start} ms)`)<br>}<br><br>// calculate answer on main thread<br>const sumNumMainMainThread = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        console.log(&#39;In main thread: calculating sum to &#39; + numToSum.value)<br>        let sum = 0;<br>        for (let i = 1; i &lt;= numToSum.value; i++) {<br>            sum += i;<br>        }<br>        console.log(&#39;In main thread: &#39; + &#39;The sum of 0 to &#39; + numToSum.value + &#39; is &#39; + sum)<br>        resolve(sum)<br>    })<br><br>}<br><br><br>// calculate the answer with web worker create from /public/worker.js<br>const sumNumWorkerPublic = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        const worker = new Worker(&#39;/worker.js&#39;)<br>        worker.postMessage(numToSum.value);<br>        worker.addEventListener(&#39;message&#39;, (e) =&gt; {<br>            if (e.data) {<br>                resolve(e.data)<br>                worker.terminate()<br>            }<br>        }, false);<br>    })<br>}<br><br>// calculate the answer with web worker create from /assets/workers/worker.js<br>const sumNumWorkerVite = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        const worker = new MyWorker()<br>        worker.postMessage(numToSum.value);<br>        worker.addEventListener(&#39;message&#39;, (e) =&gt; {<br>            if (e.data) {<br>                resolve(e.data)<br>                worker.terminate()<br>            }<br>        }, false);<br>    })<br>}<br><br>&lt;/script&gt;<br>&lt;style lang=&quot;css&quot;&gt;<br>.css_animated_part {<br>    width: 100px;<br>    height: 100px;<br>    position: relative;<br>    background-color: red;<br>    animation-name: example;<br>    animation-duration: 4s;<br>    animation-iteration-count: infinite;<br>}<br><br>@keyframes example {<br>    0% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br><br>    25% {<br>        background-color: yellow;<br>        left: 200px;<br>        top: 0px;<br>    }<br><br>    50% {<br>        background-color: blue;<br>        left: 200px;<br>        top: 200px;<br>    }<br><br>    75% {<br>        background-color: green;<br>        left: 0px;<br>        top: 200px;<br>    }<br><br>    100% {<br>        background-color: red;<br>        left: 0px;<br>        top: 0px;<br>    }<br>}<br>&lt;/style&gt;</pre><p>In the <strong>import </strong>part of the script, the worker script is imported with</p><pre>import MyWorker from &#39;@/assets/workers/workerVite?worker&#39;</pre><p>Create the worker by</p><pre>const worker = new MyWorker()</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*slMiH-CFHq3s3_LmEY5mnw.gif" /></figure><h3>Comparison:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*b2Z_vsOxy6XnDcST7GSMPQ.gif" /></figure><p>Discussion:</p><p>The worker is created to calculate the sum of 0 to 1000000000 from the “public” folder and desired path with “Vite path import”. The most obvious part is that the calculation using web workers has no side effect on the page rendering. The CSS animation goes smoothly during the calculation. Much more surprising is that the execution time spent is much less than the same calculation on the main thread. It is about 7 times faster on my device.</p><p>Both web worker hosting methods in the Nuxt3 app tested in the project perform the same well. Readers can use any method in your web app as your need.</p><p>The source code is on:</p><p><a href="https://github.com/benjamin5252/web-worker-nuxt3-example">https://github.com/benjamin5252/web-worker-nuxt3-example</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d03c1c8f2952" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>