<?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 Nick Chen on Medium]]></title>
        <description><![CDATA[Stories by Nick Chen on Medium]]></description>
        <link>https://medium.com/@ccwukong?source=rss-ba94bfb8074c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*urpSEG26D5siF9zDGGoCGA.png</url>
            <title>Stories by Nick Chen on Medium</title>
            <link>https://medium.com/@ccwukong?source=rss-ba94bfb8074c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:27:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ccwukong/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[I Built a Multi-Agent Test Harness to Audit Wall Street. Here’s How It Dissected Crocs (CROX)]]></title>
            <link>https://medium.com/@ccwukong/i-built-a-multi-agent-test-harness-to-audit-wall-street-heres-how-it-dissected-crocs-crox-06613931d1e8?source=rss-ba94bfb8074c------2</link>
            <guid isPermaLink="false">https://medium.com/p/06613931d1e8</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Nick Chen]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 02:52:06 GMT</pubDate>
            <atom:updated>2026-06-02T02:52:06.175Z</atom:updated>
            <content:encoded><![CDATA[<p>As a software engineer who spends my days architecting complex backend systems, handling webhook lifecycles, and debugging server deadloops, I am used to living in a world of deterministic logic. But when I look at retail equity research, I see nothing but emotion, narrative, and vibe-based investing.</p><p>So, I decided to treat corporate SEC filings the same way I treat a fragile codebase: I built a test harness to stress-test them.</p><p>Applying the principles of harness engineering, I constructed a proprietary multi-agent pipeline orchestrated by Bun.js and TypeScript. I deployed a “Red Team” AI agent to ruthlessly hunt for footnote anomalies, a “Verifier” to cross-reference real-time macroeconomic data, and a “CIO” agent to output cold, math-driven price bounds.</p><p>This week, I pointed my test harness at <strong>Crocs (NASDAQ: CROX)</strong> — a retail darling currently trading at a seemingly absurdly cheap 8x forward earnings.</p><p>The system’s Red Team findings were brutal. Here is Stage 1 of the audit.</p><h4>The Red Team Memo: Stripping the GAAP Illusion</h4><p>At first glance, Crocs looks like a cash-printing machine. But our Red Team agent bypassed the management’s upbeat earnings call transcript and parsed the raw 10-K data. It flagged two critical structural anomalies that are currently mispriced by the market.</p><p><strong>1. The $738M HEYDUDE Smokescreen</strong> Management is heavily promoting their “robust free cash flow,” but the system detected a massive accounting shield. Last year, Crocs took a staggering $738 million impairment charge on HEYDUDE — a brand they recently acquired. By taking this massive, one-time “paper loss,” they effectively reset the baseline. It makes their current operating margins look artificially inflated going forward, masking the fact that the actual operational integration of the HEYDUDE acquisition has been a catastrophic failure. The 8x P/E is an illusion built on written-down assets.</p><p><strong>2. The 18–20% Structural Tariff Minefield</strong> Our agent scanned the supply chain dependencies and cross-referenced them with current geopolitical risk models. Crocs relies almost entirely on five core manufacturing countries (including Vietnam and China). The system flagged an incoming 18–20% tariff threat targeting these specific regions. For a company boasting 58% gross margins, this isn’t just a headwind — it’s a direct torpedo to their bottom line. Wall Street consensus is completely ignoring this tail risk.</p><h4>The Verdict?</h4><p>The Red Team has identified the structural rot, but at what price does CROX actually become a safe, mathematically sound buy?</p><p>To answer this, my pipeline’s final stage — the <strong>CIO Adjudicator</strong> — stripped away the $738M impairment illusion, applied the tariff margin degradation, and calculated the exact <strong>Accumulate, Hold, and Trim price boundaries</strong>.</p><p>To see the live Verifier data and the definitive CIO execution ranges for CROX (and all future automated deep-dives), subscribe to <strong>The Agentic Investor</strong> on Substack.</p><p><a href="https://theagenticinvestor.substack.com/p/the-cio-verdict-executing-the-crox">The CIO Verdict: Executing the CROX Valuation Model</a></p><p><strong>🚨 Disclaimer:</strong> This article is for educational and informational purposes only. The views expressed are outputs of programmatic quantitative models and do not constitute financial, investment, or trading advice. The author is a software engineer, not a registered financial advisor. Investing in equities carries high risk; always conduct your own research (DYOR) before making financial decisions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06613931d1e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built a ‘Peter Lynch’ Stock Analyzer in Python (using yfinance)]]></title>
            <link>https://medium.com/@ccwukong/i-built-a-peter-lynch-stock-analyzer-in-python-using-yfinance-20d27b909563?source=rss-ba94bfb8074c------2</link>
            <guid isPermaLink="false">https://medium.com/p/20d27b909563</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Nick Chen]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 14:25:18 GMT</pubDate>
            <atom:updated>2026-01-03T14:25:18.718Z</atom:updated>
            <content:encoded><![CDATA[<p>Peter Lynch, the legendary Fidelity Magellan fund manager, developed a systematic approach to stock analysis that he called the “2-Minute Drill.” His methodology categorizes stocks into six types and applies specific metrics to each category.</p><p>While Lynch did this manually with pencil and paper, we can automate this entire process using Python and the yfinance library.</p><p>In this post, I’ll show you how to build <strong>“The Lynchpad”</strong> — a Python script that automatically fetches live market data and runs Lynch’s decision tree against your portfolio.</p><h3>What is Peter Lynch’s Decision Tree?</h3><p>Lynch’s approach categorizes stocks into six types:</p><ul><li><strong>Fast Growers:</strong> High-growth companies (20%+ annual growth). Watch PEG ratio and P/E.</li><li><strong>Slow Growers:</strong> Mature companies with steady dividends. Focus on dividend yield.</li><li><strong>Stalwarts:</strong> Large, stable companies. Look for reasonable P/E ratios.</li><li><strong>Cyclicals:</strong> Companies tied to economic cycles. Watch inventory vs. sales growth.</li><li><strong>Turnarounds:</strong> Distressed companies recovering. Check debt levels.</li><li><strong>Asset Plays:</strong> Companies with undervalued assets. Analyze book value.</li></ul><p>Lynch’s most important automated check is the <strong>“Inventory Warning”</strong> — if inventory is growing faster than sales, it’s a red flag that demand is slowing.</p><h3>The Use Case: “The Lynchpad”</h3><p>This script demonstrates three key capabilities that make Python perfect for investment analysis:</p><ul><li><strong>External Libraries:</strong> Import yfinance to fetch live stock data automatically.</li><li><strong>Logic &amp; Automation:</strong> Apply Lynch’s complex “inventory vs. sales” logic automatically.</li><li><strong>Human-in-the-Loop:</strong> You define the tickers and the “Story” in a dictionary, and the code handles the math.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xN_m2Vx4DjIOrNmQ.png" /></figure><p><em>The Lynchpad in action — analyzing FIG, DUOL, Z, and KO with live data</em></p><h3>The Complete Code</h3><p>Copy this code into your Python environment. It fetches live data from Yahoo Finance and applies Lynch’s decision tree automated logic:</p><pre># ==========================================<br>#  THE LYNCHPAD: AUTOMATED STOCK CHECKLIST<br># ==========================================<br># 1. Install dependency if needed: pip install yfinance<br>import yfinance as yf<br>import pandas as pd<br><br># --- USER INPUT SECTION ---<br># Define your portfolio and the &quot;Story&quot; (Lynch&#39;s 2-minute drill)<br># This shows how code mixes manual notes with automated data.<br>portfolio = {<br>    &quot;FIG&quot;:  {&quot;category&quot;: &quot;Fast Grower&quot;, &quot;story&quot;: &quot;Monopoly on design, AI integration coming.&quot;},<br>    &quot;DUOL&quot;: {&quot;category&quot;: &quot;Fast Grower&quot;, &quot;story&quot;: &quot;Strong user retention, expanding to Math/Music.&quot;},<br>    &quot;Z&quot;:    {&quot;category&quot;: &quot;Turnaround&quot;,  &quot;story&quot;: &quot;Housing market recovery play.&quot;},<br>    &quot;KO&quot;:   {&quot;category&quot;: &quot;Slow Grower&quot;, &quot;story&quot;: &quot;Defensive dividend play.&quot;}<br>}<br><br>def analyze_lynch_metrics(ticker_symbol, category):<br>    &quot;&quot;&quot;Fetches data and checks specific Lynch warnings based on category.&quot;&quot;&quot;<br>    stock = yf.Ticker(ticker_symbol)<br>    info = stock.info<br>    # 1. Basic Data<br>    price = info.get(&#39;currentPrice&#39;, 0)<br>    pe = info.get(&#39;trailingPE&#39;, 0)<br>    peg = info.get(&#39;pegRatio&#39;, 0)<br>    div_yield = (info.get(&#39;dividendYield&#39;, 0) or 0) * 100<br>    # 2. The &quot;Cyclical/Inventory&quot; Check (The most important Lynch automated check)<br>    # Warning if Inventory is growing faster than Sales<br>    inventory_warning = &quot;✅ OK&quot;<br>    try:<br>        bs = stock.quarterly_balance_sheet<br>        fin = stock.quarterly_financials<br>        # Growth calculations (Current vs Previous Quarter)<br>        inv_curr, inv_prev = bs.loc[&#39;Inventory&#39;].iloc[0], bs.loc[&#39;Inventory&#39;].iloc[1]<br>        sales_curr, sales_prev = fin.loc[&#39;Total Revenue&#39;].iloc[0], fin.loc[&#39;Total Revenue&#39;].iloc[1]<br>        inv_growth = (inv_curr - inv_prev) / inv_prev<br>        sales_growth = (sales_curr - sales_prev) / sales_prev<br>        if inv_growth &gt; sales_growth:<br>            inventory_warning = f&quot;⚠️ WARNING: Inv up {inv_growth:.1%} &gt; Sales up {sales_growth:.1%}&quot;<br>    except:<br>        inventory_warning = &quot;N/A (No Inventory Data)&quot;<br>    # 3. Category Specific Logic<br>    verdict = &quot;Hold/Neutral&quot;<br>    notes = []<br>    if category == &quot;Fast Grower&quot;:<br>        if peg &lt; 1.0: notes.append(&quot;✅ PEG is attractive (&lt;1.0)&quot;)<br>        elif peg &gt; 2.0: notes.append(&quot;❌ PEG is high (&gt;2.0)&quot;)<br>        if pe &gt; 40: notes.append(&quot;⚠️ P/E is very high&quot;)<br>    elif category == &quot;Slow Grower&quot;:<br>        if div_yield &lt; 3.0: notes.append(&quot;❌ Yield is low for this category&quot;)<br>        else: notes.append(&quot;✅ Good Yield&quot;)<br>    elif category == &quot;Turnaround&quot;:<br>        debt_equity = info.get(&#39;debtToEquity&#39;, 0)<br>        if debt_equity &gt; 100: notes.append(&quot;⚠️ High Debt Load&quot;)<br>        else: notes.append(&quot;✅ Debt manageable&quot;)<br>    return {<br>        &quot;Ticker&quot;: ticker_symbol,<br>        &quot;Price&quot;: f&quot;${price}&quot;,<br>        &quot;Category&quot;: category,<br>        &quot;P/E&quot;: f&quot;{pe:.1f}&quot; if pe else &quot;-&quot;,<br>        &quot;PEG&quot;: peg,<br>        &quot;Inv Warning&quot;: inventory_warning,<br>        &quot;Auto-Notes&quot;: &quot;; &quot;.join(notes)<br>    }<br># --- EXECUTION ---<br>print(f&quot;{&#39;TICKER&#39;:&lt;8} {&#39;PRICE&#39;:&lt;8} {&#39;CAT&#39;:&lt;12} {&#39;WARNINGS &amp; NOTES&#39;}&quot;)<br>print(&quot;-&quot; * 80)<br>for ticker, data in portfolio.items():<br>    res = analyze_lynch_metrics(ticker, data[&#39;category&#39;])<br>    print(f&quot;{res[&#39;Ticker&#39;]:&lt;8} {res[&#39;Price&#39;]:&lt;8} {res[&#39;Category&#39;][:10]:&lt;12} {res[&#39;Inv Warning&#39;]} {res[&#39;Auto-Notes&#39;]}&quot;)</pre><h3>Why This Approach Shines</h3><h3>1. “Live” Scratchpad</h3><p>Unlike a static Excel sheet, this script pulls fresh data every time you run it. You can wake up, hit “Run”, and see if metrics have changed overnight.</p><h3>2. Context + Code = Investment Journal</h3><p>You aren’t just running a script; you are maintaining the portfolio dictionary at the top. This effectively turns the code block into your Investment Journal. You can write comments right next to the ticker logic:</p><pre>&quot;FIG&quot;: {<br>    &quot;category&quot;: &quot;Fast Grower&quot;,<br>    &quot;story&quot;: &quot;Holding until $100. Watch out for Adobe competition.&quot;<br>}  # &lt;-- Your personal notes live in the code</pre><h3>3. Complex Logic Hidden</h3><p>The analyze_lynch_metrics function contains all the ugly API parsing and calculation logic, keeping your main execution loop clean and focused on the results.</p><h3>Customizing for Your Portfolio</h3><p>The beauty of the Lynchpad is its flexibility. You can easily customize it for your own investment strategy:</p><h3>Add Custom Metrics</h3><p>Want to track free cash flow or profit margins? The yfinance library provides access to hundreds of financial metrics:</p><pre># Add to the analyze_lynch_metrics function:<br>fcf = info.get(&#39;freeCashflow&#39;, 0)<br>profit_margin = info.get(&#39;profitMargins&#39;, 0) * 100<br><br>if profit_margin &gt; 20:<br>    notes.append(f&quot;✅ Strong margins: {profit_margin:.1f}%&quot;)</pre><h3>Beyond Peter Lynch</h3><p>While this example focuses on Lynch’s methodology, a live Python environment is perfect for implementing any investment strategy:</p><ul><li><strong>Value Investing:</strong> Calculate intrinsic value using DCF models</li><li><strong>Momentum Trading:</strong> Track price trends and moving averages</li><li><strong>Dividend Investing:</strong> Analyze payout ratios and dividend growth</li><li><strong>Technical Analysis:</strong> Calculate RSI, MACD, and other indicators</li></ul><p><em>This post was written using </em><a href="https://coilpad.com/"><em>CoilPad</em></a><em>, a native macOS Python playground. If you enjoyed this automated approach to stock analysis, give it a try!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20d27b909563" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 6 phases of the Node.js event loop explained]]></title>
            <link>https://javascript.plainenglish.io/node-js-event-loop-explained-d27647ec8d53?source=rss-ba94bfb8074c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27647ec8d53</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nick Chen]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 15:32:23 GMT</pubDate>
            <atom:updated>2020-09-29T18:26:11.917Z</atom:updated>
            <content:encoded><![CDATA[<h4>The different phases and the tasks that each phase handle</h4><p>Let’s look at a code snippet first:</p><pre>setImmediate(()=&gt; console.log(&#39;setImmediate&#39;));</pre><pre>fs.readFile(&#39;/etc/passwd&#39;,(err, data)=&gt;{<br>  console.log(&#39;reading file&#39;);<br>}); </pre><pre>console.log(&#39;start&#39;);</pre><pre>process.nextTick(()=&gt; console.log(&#39;nextTick&#39;));</pre><pre>setTimeout(()=&gt;console.log(&#39;setTimeout 1&#39;), 0);</pre><pre>setTimeout(()=&gt;console.log(&#39;setTimeout 2&#39;), 3);</pre><pre>let counter = 0;<br>const timeout = setInterval(() =&gt; {<br>    console.log(&#39;setInterval&#39;);<br>    if (counter &gt;= 3) {<br>        console.log(&#39;exiting setInterval&#39;);<br>        clearInterval(timeout);<br>    }<br>    counter++;<br>}, 0);</pre><pre>new Promise((resolve, reject)=&gt; {<br>  console.log(&#39;start promise 1&#39;);<br>  resolve(&#39;Promise 1&#39;);<br>}).then(data=&gt; {<br>  console.log(data);<br>})</pre><pre>console.log(&#39;end&#39;);</pre><p>What would be the output of this program?</p><p>In order to answer the question, we’ll need to understand 2 things:</p><ul><li>The different phases in the event loop.</li><li>The tasks each phase will handle.</li></ul><h3>The 6 phases</h3><p>When Node.js finished executing the index.js in the main thread, the Node.js event loop starts to execute the callbacks registered during the main thread’s runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZlD-iqmcgSWEHptT.png" /></figure><h3>Callback queue</h3><p>There’s a callback queue in each phase that stores callbacks to be executed in that phase. It’s very similar to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide">Task queue</a> provided by a browser.</p><h3>Timers</h3><p>This is the first phase in the event loop. It finds expired timers in every iteration (also known as Tick) and executes the timers callbacks created by setTimout and setInterval.</p><p>For example:</p><pre>setTimeout(() =&gt; console.log(&#39;Timeout 1&#39;), 0);</pre><pre>setTimeout(() =&gt; console.log(&#39;Timeout 2&#39;), 10);</pre><p>Timeout 1 will be printed in the first iteration because the first timer expires after 0ms. However, Timeout 2 will be printed in another iteration (not necessarily in the second iteration) because the second timer expires after 10ms.</p><h3>Pending callbacks</h3><p>It handles I/O callbacks deferred to the next iteration, such as handling TCP socket connection error.</p><h3>Idle, prepare</h3><p>It’s only used internally.</p><h3>Poll</h3><p>The Poll phase calculates the blocking time in every iteration to handle I/O callbacks. In this phase, the epoll_wait() system call is invoked (in Linux).</p><h3>Check</h3><p>This phase handles the callbacks scheduled by setImmediate(), and the callbacks will be executed once the Poll phase becomes idle.</p><h3>Close Callback</h3><p>This phase handles callbacks if a socket or handle is closed suddenly and the ‘close’ event will be emitted.</p><h3>The microtask queue</h3><p>The microtask queue stores microtasks (callbacks) created by:</p><ul><li>process.nextTick()</li><li>then() and catch() that handle resolved and rejected promises</li></ul><p>Microtasks are executed after the main thread and each phase of the event loop. Microtasks created by process.nextTick() are executed before those created by then() and catch().</p><p>For example:</p><pre>Promise.reject(() =&gt; {}).catch(() =&gt; {<br>  console.log(&#39;rejected promise&#39;);<br>});<br>setTimeout(() =&gt; console.log(&#39;Timeout 1&#39;), 0);<br>process.nextTick(() =&gt; console.log(&#39;nextTick&#39;));<br>setTimeout(() =&gt; console.log(&#39;Timeout 2&#39;), 10);</pre><p>The output is:</p><pre>nextTick // the callback created by process.nextTick() executed before catch()<br>rejected promise<br>Timeout 1<br>Timeout 2</pre><p>The Node.js event loop workflow eventually looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3KzxMxOA4H6h_Uzy.png" /></figure><p>Let’s look at the example again.</p><pre>setImmediate(() =&gt; console.log(&#39;setImmediate&#39;));</pre><pre>fs.readFile(&#39;/etc/passwd&#39;, (err, data) =&gt; {<br>  console.log(&#39;reading file&#39;);<br>});</pre><pre>console.log(&#39;start&#39;);</pre><pre>process.nextTick(() =&gt; console.log(&#39;nextTick&#39;));</pre><pre>setTimeout(() =&gt; console.log(&#39;setTimeout 1&#39;), 0);</pre><pre>setTimeout(() =&gt; console.log(&#39;setTimeout 2&#39;), 3);</pre><pre>let counter = 0;<br>const timeout = setInterval(() =&gt; {<br>  console.log(&#39;setInterval&#39;);<br>  if (counter &gt;= 3) {<br>    console.log(&#39;exiting setInterval&#39;);<br>    clearInterval(timeout);<br>  }<br>  counter++;<br>}, 0);</pre><pre>new Promise((resolve, reject) =&gt; {<br>  console.log(&#39;start promise 1&#39;);<br>  resolve(&#39;Promise 1&#39;);<br>}).then((data) =&gt; {<br>  console.log(data);<br>});</pre><pre>console.log(&#39;end&#39;);</pre><p>The JavaScript code in the main thread is executed synchronously first:</p><pre>console.log(&#39;start&#39;);<br>console.log(&#39;start promise 1&#39;);<br>console.log(&#39;end&#39;);</pre><p>Then the callbacks in the microtask queue registered by process.nextTick(), then() and catch() in the main thread:</p><pre>console.log(&#39;nextTick&#39;);<br>console.log(data); // Promise 1</pre><p>Once the main thread clears the microtask queue, the execution enters the Timer phase of the event loop and executes the callbacks with an expired timer:</p><pre>console.log(&#39;setTimeout 1&#39;);<br>console.log(&#39;setInterval&#39;);</pre><p><em>The second callback may not be executed during the first iteration because it expires in 3ms, so its execution would be deferred to the next iteration.</em></p><p><em>In the Timer phase, there’s a callback scheduled by</em><em>setInterval()and fired repeatedly in an interval of 0ms (4 times until the timer is canceled). However, each callback execution is in a separate iteration.</em></p><p>Next, the callbacks in the Poll phase should be executed. But it takes some time to complete the file reading operation on /etc/passwd . Therefore, the Poll phase will stay idle for a while, and the event loop will proceed to the Check phase because there&#39;s a timer scheduled by setImmediate().</p><p>During the Check phase, the callback scheduled by setImmediate()will be executed :</p><pre>console.log(&#39;setImmediate&#39;);</pre><p>So far, the first iteration of the event loop has been completed.</p><p>So the event loop continues the second iteration and enters the Timer phase again to execute the remaining callback in its callback queue:</p><pre>console.log(&#39;setTimeout 2&#39;);<br>console.log(&#39;setInterval&#39;);</pre><p>Then it enters the Poll phase, and since there are no more timers scheduled by setImmediate, it waits for the callback of the file reading operation and executes the callback:</p><pre>console.log(&#39;reading file&#39;);</pre><p>And the event loop repeats iterations until it has nothing to do, so the Node.js process ends.</p><p>The final output of the example:</p><pre>start<br>start promise 1<br>end<br>nextTick<br>Promise 1<br>setTimeout 1<br>setInterval<br>setImmediate<br>setTimeout 2<br>setInterval<br>reading file<br>setInterval<br>setInterval<br>exiting setInterval</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*s-sOyyG8NoRbKpCG_y4Cmw@2x.png" /><figcaption><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw">Subscribe to Decoded, our official YouTube channel!</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27647ec8d53" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/node-js-event-loop-explained-d27647ec8d53">The 6 phases of the Node.js event loop explained</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[V8 for Node.js developers at a glance]]></title>
            <link>https://javascript.plainenglish.io/v8-for-node-js-developers-at-a-glance-129d7777456?source=rss-ba94bfb8074c------2</link>
            <guid isPermaLink="false">https://medium.com/p/129d7777456</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[v8-engine]]></category>
            <dc:creator><![CDATA[Nick Chen]]></dc:creator>
            <pubDate>Wed, 15 Jul 2020 01:54:31 GMT</pubDate>
            <atom:updated>2020-07-17T13:42:33.632Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a JavaScript engine?</h3><p>In a nutshell, a JavaScript engine is a runtime that executes JavaScript source code. A JavaScript engine should have the following components:</p><p><strong>Parser</strong></p><p>A Parser compiles JavaScript source code into an abstract syntax tree, and in some engines, the Parser also converts the abstract syntax tree into a piece of intermediate bytecode.</p><p><strong>Interpreter</strong></p><p>An Interpreter accepts, interprets, and executes the intermediate bytecode generated by the Parser.</p><p><strong>JIT Compiler</strong></p><p>A JIT Compiler converts intermediate bytecode into machine code as quickly as possible.</p><p><strong>Garbage Collector(GC)</strong></p><p>A Garbage Collector is responsible for garbage collection.</p><p><strong>Profiler</strong></p><p>A Profiler gathers information in the engine to help to improve the performance and efficacy of the engine.</p><p>Here are some popular JavaScript engines:</p><ul><li><a href="https://v8.dev/">V8</a>, a masterpiece of Google, it powers Chromium-based browsers and Node.js.</li><li><a href="https://github.com/WebKit/webkit/tree/master/Source/JavaScriptCore">JavaScriptCore</a>, from Apple, used by Webkit-based browsers, such as Safari.</li><li><a href="https://github.com/microsoft/ChakraCore">Chakra</a>, from MicroSoft and used by the newer versions of Internet Explorer.</li><li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a>, developed by Mozilla and used by Firefox.</li></ul><h3>Introduction to V8</h3><p>V8 is a JavaScript engine written in C++ and open-sourced by Google. It runs on Linux, macOS and Windows and it’s the engine powers Chrome and Node.js.</p><p>There are 4 key components in V8:</p><h4>Parser</h4><p>It parses JavaScript source code into an Abstract Syntax Tree.</p><h4>Ignition, the interpreter</h4><p>It has 2 key components: <strong>The Bytecode Generator</strong> converts an Abstract Syntax Tree into bytecode, and <strong>the Bytecode Interpreter</strong> interprets(executes) the bytecode.</p><p>While Ignition executes the bytecode, some feedback such as the number of times the bytecode executed is collected via inline cache. If the same bytecode has been executed many times, it will be marked as <strong>HotSpot</strong> and sent to TurboFan for further optimization.</p><h4>TurboFan, the JIT optimizing compiler</h4><p>TurboFan compiles the HotSpot bytecode into machine code and stores it. When the bytecode is executed next time, it will replace the original bytecode with the machine code, which greatly improves the effectiveness of the bytecode execution.</p><p>In addition, when TurboFan determines that a piece of bytecode is no longer a HotSpot, it will perform a deoptimization process, discard the optimized machine code, and then return it to Ignition.</p><p>The entire workflow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*iXkeO4hMf8Ib3h-E1GiUxQ.png" /></figure><h4>Orinoco, the garbage collector(GC)</h4><p>The previous GC mechanism in V8 took a simple sequential Stop-The-World(STW) approach, it was a total disaster for some mission-critical applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*d-H_KKalto6l26JfLWPARA.png" /></figure><p>Instead of abandoning the STW mechanism, Orinoco takes a smarter approach to improve GC performance. It uses parallel, concurrent and incremental techniques to significantly reduce the burden of garbage collecting in the main thread.</p><h4>Parallel</h4><p>The main thread and multiple helper threads work on GC tasks simultaneously so the total Stop-The-World time is shortened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*vAd-9OGyokJOtzu1ZBIGvA.png" /></figure><h4>Concurrent</h4><p>The main thread only executes JavaScript, and the helper threads handle all garbage collection work in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*9_Sg2lzY9H54UJ6Tjp8xbQ.png" /></figure><h4>Incremental</h4><p>The JavaScript executes intermittently in the main thread and the garbage collection work is split into smaller fragments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*kOBrTaxIPgbl6WGrw2h3Nw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=129d7777456" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/v8-for-node-js-developers-at-a-glance-129d7777456">V8 for Node.js developers at a glance</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[Creating realtime socket connection using AWS API Gateway and Lambda function]]></title>
            <link>https://medium.com/@ccwukong/creating-realtime-socket-connection-using-aws-api-gateway-and-lambda-function-37d31c1b88f4?source=rss-ba94bfb8074c------2</link>
            <guid isPermaLink="false">https://medium.com/p/37d31c1b88f4</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[aws-lambda-functions]]></category>
            <category><![CDATA[realtime-applications]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nick Chen]]></dc:creator>
            <pubDate>Sun, 06 Oct 2019 07:29:05 GMT</pubDate>
            <atom:updated>2019-10-07T12:14:10.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating realtime WebSocket connection using AWS API Gateway and Lambda function</h3><p>Lately, I’ve been exploring alternatives to Socket.IO, and I found AWS API Gateway already supports WebSocket APIs without needing a long-running server, thus I decided to give a try with this exciting feature.</p><p>Before starting to work on AWS, I installed a WesSocket client tool <a href="https://github.com/websockets/wscat">https://github.com/websockets/wscat</a> for testing later.</p><p>Now I can begin to create a testing WebSocket API:</p><p>Firstly, I named the new API <strong>my-test-ws</strong> and entered <strong>$request.body.action </strong>as value for the field <strong>Route Selection Expression, </strong>and<strong> </strong>it will be used as the key for the <strong>route</strong> in the incoming JSON payload sent from the client to API Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xajXx1LNT_HvkL2YT_ch2A.png" /></figure><p>Let me further explain the <strong>route</strong> part. The route is similar as <strong>Resources</strong> section in API Gateway with REST protocol. And each route is like a REST API endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*5tsCVPOdP_zD5hNIzQHQ1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*ofChUN0TrnoGwApi0X4RNQ.png" /><figcaption>API Gateway with REST protocol</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*mXpE-1orsdAfZ-PYtJnNZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*GSWBM1bKSdNR2uYx1uQHcw.png" /><figcaption>API Gateway with WebSocket protocol</figcaption></figure><p>In a WebSocket API, there are 3 pre-defined routes created by default: <strong>$connect</strong>, <strong>$disconnect</strong> and <strong>$default</strong>:</p><ul><li>The <strong>$connect</strong> route will be called when a persistent connection between client and API Gateway is established.</li><li>The <strong>$disconnect</strong> route will be called when a client is disconnected from API Gateway</li><li>The <strong>$default</strong> route will be called when there’s no matching routes in the API, and usually it’s used to handle some unexpected errors</li></ul><p>Each route could be mapped to an<strong> Integration type</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ctqjxPES3hbBh0juV3A0Ow.png" /></figure><p>It allows me to use separate lambda functions to handle each pre-defined route.</p><p>For testing purpose, I just set the <strong>Integration type</strong> to <strong>Mock</strong> for all pre-defined routes(<strong><em>If you skipped this you may get errors when you deploy the API</em></strong>).</p><p>Let’s continue the WebSocket setup. I created a new route <strong>inAppMessage </strong>with <strong>Integration type </strong>set to Lambda Function, and I will send a testing message to the WebSocket API later by indicating the designated route <strong>inAppMessage </strong>in JSON format <em>{“action”: “</em><strong><em>inAppMessage</em></strong><em>”}</em> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsmN-svqgKPrP50KCN_3bA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZK53-rsA0ztgCtZfDI1WA.png" /></figure><p>Next, click on <strong>Add integration response. </strong>This step is crucial for sending response from the lambda function to a client app(<em>I will need to create a new lambda function </em><strong><em>my-test-lambda </em></strong><em>later</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCkywdb3o0EA7V_x4CJXmw.png" /></figure><p>A route w/o integration response looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwFC6gAiMT_RgSh7W2dFzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*piUgEkekEIgmRp2cDGDIug.png" /><figcaption><strong>Left</strong>: without integration response, <strong>Right</strong>: with integration response</figcaption></figure><p>Now, let’s deploy the API with a new stage called <strong>dev</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*R3DkOetC-fjXtJK5fG-VBg.png" /></figure><p>Once I deployed the API successfully, the WebSocket URL and Connection URL are immediately available in my <strong>dev</strong> stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzNsNDLFbub6hxPG3KK-wQ.png" /></figure><p>The WebSocket URL is used to send messages from client to API Gateway, and the Connection URL is used other way round. I will demonstrate it later.</p><p>Kewl, we are done with the API Gateway setup, for now.</p><p>Next, I should work on the lambda function. Here’s my lambda function code written in Node.js for simple testing:</p><pre>&#39;use strict&#39;;<br> <br>const AWS = require(&#39;aws-sdk&#39;);</pre><pre>exports.handler = async event =&gt; {  <br>  try {    <br>    const apigatewayManagementApi = new  AWS.ApiGatewayManagementApi({      <br>  apiVersion: &#39;2018-11-29&#39;,      <br>  endpoint: &#39;<strong><em>API_GATEWAY_ID</em></strong>.execute-api.ap-southeast-1.amazonaws.com/dev&#39;,   <br>  });</pre><pre>  const params = {      <br>    ConnectionId: event.requestContext.connectionId,      <br>    Data: &#39;Sent from lambda function&#39;,    <br>  };     </pre><pre>  await apigatewayManagementApi.postToConnection(params).promise();<br>} catch (err) {    <br>  console.log(err);  <br>}};</pre><p>In order to send messages directly to a Connection URL in API Gateway from the lambda function, I will need to sign my request with <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature 4</a>, or use <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/ApiGatewayManagementApi.html"><strong>ApiGatewayManagementApi</strong></a><strong> </strong>class<strong> </strong>provided<strong> </strong>in aws-sdk.</p><p>The endpoint field is the API Gateway endpoint without the protocol prefix:</p><pre>endpoint: ‘<strong><em>API_GATEWAY_ID</em></strong>.execute-api.ap-southeast-1.amazonaws.com/dev’,</pre><p>The final step is deploying the lambda function named <strong>my-test-lambda </strong>on AWS. I’m not gonna demonstrate the steps here since there are different ways to do it. You can follow this tutorial in case you don’t know how: <a href="https://docs.aws.amazon.com/toolkit-for-eclipse/v1/user-guide/lambda-tutorial.html">https://docs.aws.amazon.com/toolkit-for-eclipse/v1/user-guide/lambda-tutorial.html</a></p><h3><strong>Demo time!</strong></h3><p>Connected to the WebSocket using wscat:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*enebZoJ-Q-EHGPaCENlGnA.png" /></figure><p>Then sent the message in JSON format to the API Gateway WebSocket:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*x0rgQCI4a8YNoZ6iGSGNKA.png" /></figure><p>Then I got the message sent from the lambda function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*3QQpSywVu92ohkHLYBfMmQ.png" /></figure><h3><strong>Important!</strong></h3><p>There are some gotchas in API Gateway WebSocket:</p><ul><li>The <strong>connectionId</strong> is issued by API Gateway when there’s a new connection established from client to WebSocket. Each connection can only last for 2 hours(enough for 99% use cases IMO), however, if the connection has been in idle state(no data sent to the WebSocket) for 10 minutes, the connection will be timeout.</li><li>The message payload size is up to 128 KB with a maximum frame size of 32 KB. If a message exceeds 32 KB, you must split it into multiple frames, each 32 KB or smaller.</li></ul><p>For more specifications, please read this article: <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-known-issues.html">https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-known-issues.html</a></p><p>Happy hacking:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37d31c1b88f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>