仓库源文站点原文


layout: "../layouts/BlogPost.astro" title: "TIL" slug: today-i-learned description: "" added: "" top: true

order: 1

  1. major.minor.patch version (also known as breaking.feature.fix): ^ instructs npm to install the newest version of the package with the same major version; Use ~ to have both the major and minor version match.
  2. __dirname and __filename: running node example.js from /Users/mjr, __dirname is /Users/mjr and __filename is /Users/mjr/example.js. __dirname returns the directory name of the directory containing the JavaScript source code file, while process.cwd() returns the current working directory in which you invoked the node command. However __dirname can't be used in ESM projects. The equivalent way is to use something like fileURLToPath(new URL('.', import.meta.url)), which ensures a cross-platform valid absolute path string. (import.meta.dirname and import.meta.filename are available in Node v20.11.0 LTS.)
  3. path.resolve() and path.join(): path.resolve creates absoulte path from right to left until an absolute path is constructed, whereas path.join simply concatenates every parameter from left to right whether they have / or not. TypeError is thrown if any of the arguments is not a string.
  4. Quickly browse the history of a file in the repo: Go to a file in GitHub (or GitLab, or Bitbucket), replace github.com with github.githistory.xyz (i.e. https://github.githistory.xyz/kexiZeroing/FE-Learning-notes/blob/master/README.md)
  5. One second to read GitHub code with VS Code online. Just add 1s after github (github1s.com) in browser address bar for any repository you want to read. Another one, open a GitHub repo, press ., then VS Code opens up in your browser. You can also change github.com to github.dev in the URL in order to achieve the same effect.
  6. Type Cmd + K to open the GitHub command palette to quickly navigate, search projects and try other commands. There is a related React component cmdk.
  7. Cmd + Shift + . toggles hidden files in Mac.
  8. After Cmd + h to hide the window, there is no shortcut to bring the window back, because the app loses focus when hidden. The easiest way to do is using task switcher Cmd + Tab to display it normally.
  9. Open VSCode in terminal: Cmd + Shift + P -> type Shell Command: Install 'code' command in PATH -> restart the terminal for the new $PATH value to take effect, and type code . to open VS Code. (open . to open the Finder)
  10. Open settings.json file in VSCode: Cmd + Shift + P, type "open settings" and you can choose Open User Settings (JSON). Another way is Cmd + , to open Settings UI and there is a button on the top-right corner which can be used to switch between JSON and graphical view.
  11. Use "Organize Imports" in VS Code to remove unused imports. Run it via the command palette or add this to settings.json to run automatically on save. In addition, you can use up and down keys in the search box to access your search history. Use Ctrl + G to navigate to a specific line. Also, Cmd + X to delete a line, Cmd + L to select a line, Opt + Up/Down to move a line.
  12. Drag the file tab from VS Code into the terminal to get the absolute path for that file.
  13. Browser notepad: data:text/html,<html contenteditable>. The world smallest office suite is worth to check out.
  14. Ever struggled with some forgotten processes taking over a port you're trying to use? Just run npx kill-port [port-number]. In addition, fkill is an awesome CLI tool that lets you kill hanging processes npx fkill. Check more at kill-port and fkill-cli.
  15. Type env or printenv in the terminal to list all the default environment variables. The env command can run other commands with modified environments. If no command is given, env prints environment variables. printenv can only print environment variables and cannot run commands.
  16. Install tldr-pages npm install -g tldr which simplify the man pages with practical examples, e.g. try to run tldr tar or tldr git branch.
  17. m-cli is a macOS command line tool (Swiss Army Knife for macOS) that lets you interact with utilities and applications entirely in Terminal. Run m to display all the available commands.
  18. Short link react.new, vue.new, ng.new, js.new, csb.new to create a new codeSandbox project. Stackblitz is another similar platform and might be the most exciting in-browser IDE (try vite.new, remix.new, node.new). All code execution in StackBlitz happens within the browser security sandbox and cannot break out to your local machine. (not on remote VMs or local binaries)
  19. Use if (typeof window === 'undefined') to execute code only in the server-side. We can’t do it using if (window === undefined) because we’d get a “window is not defined” runtime error.
  20. du command is used to display disk usage statistics. It calculate and print the disk space used by files or directories. -a option means display an entry for each file; -s will summarize and show only the total size of the directory; -h for human-readable output.
  21. You can set the parameters of the function passed to setInterval and setTimeout by specifying extra arguments in the call, e.g. setTimeout(console.log, 1000, 'hello');
  22. Scroll the window to a particular place in the document, window.scroll({top: 100, left: 100, behavior: 'smooth'}); or setting in CSS html { scroll-behavior: smooth; }
  23. Conditionally add a member to an object: const item = {... true && {bar: 'bar'}, ... false && {falsy: 'falsy'}};, and the item will be {bar: "bar"}
  24. GNU (GNU's Not Unix, it is pronounced g'noo, like saying "grew" but replacing the r with n) is a collection of programs which help to create a fully functional operating system. GNU's goal was to create a fully free, open source replacement of Unix. Linux functions as an operating system kernel but the Linux kernel alone does not form a working operating system. When Linux was created, there were many GNU components already created but GNU lacked a kernel, so Linux was used with GNU components to create a complete operating system. We prefer to use the term "GNU/Linux" to refer to systems that many people casually refer to as “Linux”.
  25. If you want to distinguish zsh script files, then you can change the script’s file extension from .sh to .zsh. But the file extension will have no effect on which interpreter will be used to run the script. That is determined by the shebang, the extension only provides a visible clue in the Finder or Terminal.
  26. All shells originate from the Bourne Shell, called sh. Bash means Bourne Again SHell. sh was proprietary and not open source, but Bash is created as a free alternative for the GNU project. It offers functional improvements over sh for both programming and interactive use.
  27. Terminal in the software sense can take input and pass it on. It's good at displaying textual output, but the Terminal doesn't actually process your input. Technically Console is a device (has screen and keyboard) and Terminal is the software program inside the Console. In the software world a Terminal and a Console are synonymous. A shell is the program that the Terminal sends user's input to. The shell generates output and passes it back to the Terminal for display. Your choice of shell doesn't and shouldn't dictate your choice of terminal application. (Shell: bash, fish, zsh, PowerShell, cmd; Console/Terminal: Hyper, cmder, MinTTY, Windows Terminal, VSCode includes a Terminal).
  28. A local shell variable can be declared using = sign (should not be any spaces between a variable's name, = and its value) and its value can be retrieved using the $ sign. Because using $ to identify variables, you need to escape it if you want to remove a file whose name contains a $ , like rm -r \$RECYCLE.BIN.
  29. In Bash scripts, positional parameter $0 is the script's name, and $1 … $9 are parameter list elements from 1 to 9. If you execute ./script.sh Hello World, it will make $0 = ./script.sh, $1 = Hello, $2 = World. And $# means the number of positional parameters of your script, which is typically used to ensure a parameter is passed.
  30. Using exit and a number is a handy way of signalling the outcome of your script. Non-zero exit indicates an error (exit 1). Zero indicates success (exit 0). $? returns the exit value of the last executed command.
  31. By defualt, bash will continue after errors. To exit the script as soon as one of the commands failed, add set -e at the beginning.
  32. The javascript void operator evaluates the given expression and then returns undefined. It is often used merely to obtain the undefined primitive value, usually using void(0) (which is equivalent to void 0). Arrow functions with a short-hand braceless syntax will return an expression. This can cause unintended side effects by returning the result of a function that previously returned nothing. To be safe, when the return value is not intended to be used, it can be passed to the void operator.
  33. Browser sync local server: npx browser-sync start --server --files ".". It watches all files in the current folder (and all subfolders) for changes and launches a web server on port 3000. Any time you change a file, the browser will refresh. Run browser-sync start --help for more information.
  34. http-server is a simple static HTTP server: npx http-server. Serving defaults to ./public if the folder exists, and ./ otherwise. index.html will be served as the default file to any directory requests. You can also configure the Port, CORS, Cache, HTTPS, Proxy (proxies all requests which can't be resolved locally to the given url), etc.
  35. Use JSON Placeholder, DummyJSON or JSON Server to get a full fake REST API when a quick back-end is needed for prototyping and mocking.
  36. httpstat.us is a super simple service for generating different HTTP codes. It can be used to get proper headers for each error type. Just add the status code you want to the URL like https://httpstat.us/500
  37. GitHub pages is a free way to host projects. It has two types of pages: User pages or Project pages. User pages is for hosting a personal website or a portfolio. You can only have one user page attached to your GitHub account and the URL will be yourusername.github.io. Project pages is used to host a project and you can create multiple project pages per account. Github uses gh-pages branch to get files to build and publish from. The URL for this page will be yourusername.github.io/projectname.
  38. Just-in-Time (JIT) vs Ahead-of-Time (AOT) compilation in Angular: JIT compiler runs on client side in the browser. It performs a lot of work to analyze application’s directives and components at runtime and generate code in memory. When the page is refreshed, all the work that has been done is thrown away, and the JIT compiler does the work all over again. AOT compiler runs on server sidee at build time (in other words, before the actual execution of the code). The browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application faster. We also don't ship @angular/compiler code in our production bundle anymore.
  39. With an interpreter, the "translation" happens pretty much line-by-line, on the fly. But the con of using an interpreter comes when you’re running the same code more than once. JavaScript started out slow (using interpreter, i.e., if you’re in a loop, you have to do the same translation over and over again), but then got faster thanks to JIT. It makes JavaScript run faster by monitoring the code as it’s running it and sending hot code paths to be optimized. If the same lines of code are run a lot, the JIT will send it off to be compiled and store that compilation.
  40. Babel compiles JSX <div>Hi</div> to a function call React.createElement('div', null, 'hi'). If you have a comment like /** @jsx cool */, Babel will transpile the JSX using the function cool you defined instead of React.createElement, so you can have a function const cool = (el, props, ...children) => {}, which could be totally not related to React.
  41. Ever tried debugging an element (e.g. input dropdown) that keeps disappearing when it loses focus once you start using devtools? Cmd + Shift + P, then type "Emulate a focused page". Another way to freeze UI, open up the devtools source panel and use Cmd + \ to pause script execution. Run setTimeout(() => { debugger } , 2000) is also a good solution. (Note that here debugger is a statement rather than an expression, so we need wrap it in a function.)
  42. Take screenshots using devtools: Cmd + Shift + P, then type "screenshots". You can choose an area screenshot (drag to select), a full website screenshot, an HTML node screenshot (need to select an element first) or a current viewport screenshot.
  43. Hacks for playing html video: $0 to get the element you inspected, and if it's a <video>, change playback speed $0.playbackRate = 2 or show picture-in-picture mode $0.requestPictureInPicture().
  44. You could type document.designMode = 'on' in devtools console to make your whole website editable, which great to test different texts.
  45. In devtools console, you can use $ and $$ as shortcuts for document.querySelector() and document.querySelectorAll() respectively ($$ returns a true array instead of an array-like NodeList). For example, you can use console.table($$('img').filter(i => !i.alt), ['src']) to have the list of image URLs that don't have an alternative text. Furthermore, $0 gives you the reference to the currently selected element. $1 is the previously selected element. That goes all the way to $4. Use $_ to get the result of the last evaluated expression in the console. What's more, getEventListeners($0) returns the event listeners registered on the specified object.
  46. copy(anything) is a handy utility in the console that allows you to put anything into the system clipboard. Furthermore, If you have debug(function) in the console, when the specified function is called, the debugger is invoked and breaks inside the function on the Sources panel.
  47. At the top right hand side of "Sources" tab, there is a button 'Deactivate breakpoints' - Cmd + F8 to stop the browser from going into debug mode (the execution won't stop). Another option is to right-click the line next to the debugger statement and select "Never pause here". It is especially useful when you try to inspect websites not under your control that left breakpoints in the source code, that might have been done intentionally to prevent you from doing inspection.
  48. When you delete files, the data is not initially removed from the hard disk. Instead, the space on the disk that was occupied by the deleted data is deallocated. After it is deallocated, the space is available for use when new data is written to the disk. Until the space is overwritten, you can recover the deleted data by using a low-level disk editor or data-recovery software.
  49. The <a> tag has the ping attribute, which specifies a URL that will be called when the link is clicked. The URL would get a POST message with the content "PING" (literally) and the ping-to request header holds the link's destination, which can be used for tracking purposes and providing stats and information about how the visitors used the site.
  50. Why I don't need to clean up my downloads folder in macOS? There's the /tmp directory (symlinking to /private/tmp). This directory is used for temporary operating system files, and it's automatically cleaned up after you reboot your machine. I configure the browser to store downloads by default in /private/tmp.
  51. process.argv (full form is argument vector) returns an array containing the command-line arguments passed when the Node.js process was launched. The first element will be the 'node', the second element will be the name of the js file. The next elements will be any additional command line arguments.
  52. If you open so many tabs, I just discovered that Chrome offers a UI (chrome://discards) to discard tabs (put them to sleep) to free up system resources.
  53. When you create a new app using npx create-react-app, the CLI will use Yarn to install dependencies (that's why you can see yarn.lock). If you have Yarn installed, but would prefer to use npm, you can append --use-npm to the creation command.
  54. Either with window.open() or by navigating a link with a target attribute, if noreferrer is set, the browser will omit the Referer header, as well as set noopener to true. noopener means the new window will not have access to the originating window via window.opener and returns null. All major browsers (i.e. Chrome 88) implicitly set rel="noopener" for any target="_blank" link by default. (This has been the case in every browser for 3+ years.)
  55. Shell executes command in the simplified version of steps: prints the prompt and waits for input -> splits this line of command into tokens -> checks if the first token is aliased -> checks if the command is builtin -> searchs in the PATH env if the command is not builtin (ls is found in /bin/ls) -> creates a new process to execute it by using system call. If you are curious to know where the program is stored, which command will help you to identify the path and add -a option (which -a ls) to display all the paths for that specified command.
  56. file command is used to determine the file type/encoding (file xyz.txt or file *), but note that it reads only part of the file and takes a best guess with the help of a magic file that contains all the patterns to recognize a file type. iconv command is used to convert text from the encoding given for the -f option to the encoding given for the -t option. iconv -l lists the names of the supported encodings in a system dependent format.
  57. Ctrl-C sends a SIGINT (Signal interrupt) to the foreground process, which by default translates into terminating the application. Ctrl-D sends an EOF character, which bash interprets as a desire to exit.
  58. dig command (Domain Information Groper, replacement for nslookup) is used to gather DNS information. Type dig xxx.com to perform a DNS lookup. The most important section is the ANSWER section which displays the IP address associated with the domain name. By default dig requests the A record and uses the local configuration listed in /etc/resolv.conf to decide which name server to query. To specify a name server against which the query will be executed, use dig xxx.com @8.8.8.8. To find the alias domain name, use the cname option dig xxx.com cname.
  59. A 32 bit IPv4 address is an A record. The AAAA record is similar to the A record, but it allows you to specify the IPv6 address of the server. IPv6 is four times the size – 128 bits – so it ended up being a quad-A record. You can use dig to determine the AAAA record associated with a domain name dig AAAA example.com.
  60. All DNS records actually end with the period character (.) which represents the root of the DNS hierarchy, but it's rarely printed and is usually just assumed. A domain name that includes the trailing period character is said to be a fully-qualified (unambiguous) DNS domain name.
  61. whois command to find out information about a domain, such as the owner of the domain, the owner’s contact information, and the nameservers that the domain is using. openssl s_client -connect servername:443 would be used to connect to an SSL HTTP server, maybe for checking certificate validity.
  62. A landing page (people arrive at after clicking on a link in an email or an ad from a search engine) is a standalone web page designed to increase the conversion rates of marketing campaigns, so the primary goal is to keep users there until they convert. A splash page (appear while a game or program is launching) covers up the site before entering and have more animations, videos, and eye-catching elements. It has an exit link that redirects visitors to the main/home page.
  63. ORM is Object Relational Mapping, basically a technique that lets you query and manipulate data from a database using an object-oriented paradigm. With the help of ORM, you don’t actually need to use SQL at all. You can directly interact with the database and perform queries in the same language you are using for your back-end code. ODM is Object Document Mapping. It is like an ORM for non-relational databases. Mongoose is a good example for ODM for MongoDB.
  64. Two popular choices for ORM in the TypeScript ecosystem are Prisma and Drizzle. Prisma offers a more abstracted, developer-friendly approach, while drizzle, which is relatively new, provides a closer-to-SQL experience (composing SQL queries with JavaScript/TypeScript functions) with type safety.
  65. Node process.platform returns a string identifying the operating system platform on which the Node.js process is running: darwin, linux, win32. Darwin is the part of OS X that is the actual operating system, which forms the core set of components upon which Mac OS X and iOS are based. To give an analogy, Darwin would be the equivalent of Linux while Mac OS X would be the equivalent of Ubuntu or another distribution.
  66. btoa() "binary to ASCII" method creates a Base64-encoded ASCII string from a binary string (a String object in which each character is treated as a byte of binary data). atob() "ASCII to binary" decodes a string of data which has been encoded using Base64 encoding. atob() throws error if encodedData is not valid base64. Note that base64 are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with ASCII.
  67. Pause script execution when the DOM changes which is useful if you don't know the codebase you are debugging: Navigate to the Elements panel -> Find the node which you want to add the breakpoint on -> Right click and check the Break on sub menu -> Choose the type of breakpoint (subtree modification, attribute modification, node removal)
  68. If you want to hide resources loaded by browser extensions in the Network panel, type -scheme:chrome-extension in the filter input box (putting a - in front means to negate the search, or use the invert checkbox next to it). Chrome 117 has a new filter called "Hide extension URLs" that does the same thing. Similarly use status-code:404 to find all requests that ended up in a 404 error.
  69. Media Source Extensions provides functionality enabling plugin-free web-based streaming media. Using MSE, media streams can be created via JavaScript. MediaSource is an object representing the video’s data, and we're not adding a link to the video (mp4 file), we're adding a link to the MediaSource object. Older versions of the Media Source specification required using URL.createObjectURL() to create an object URL then setting src to that URL. Now you can just set srcObject to the MediaStream directly.
  70. Zero Width Joiner (ZWJ, pronounced "zwidge") is a Unicode character that joins two or more other characters together in sequence to create a new emoji. This is an invisible character when used alone and the code point is U+200D. When a ZWJ is placed between two emoji characters, it can result in a single glyph being shown, such as the family emoji 👨‍👨‍👦 👨‍👩‍👧‍👦, made up of two adult emoji and one or two child emoji.
  71. A software license is a legal instrument spelling out what can and can’t be done with software. MIT is probably the one you’ve seen the most and is one of the most permissive licenses you can place on software. It pretty much says that you can do anything you want with the software without any issues, the only thing asked of you is to include a copy of the original copyright and license notice with every copy of the software. A lot of famous software use this license such as Node.js, Vuejs, Ruby on Rails. The ISC license (comes default with npm init) is essentially the same as MIT but without the clauses that would be considered extraneous.
  72. Every test you write will include selectors for elements. Targeting a element by tag, class or id is very volatile and highly subject to change. Instead, adding data-test, data-testid, or data-cy (using Cypress) attribute to the element gives us a targeted selector that's only used for testing, which isolate them from CSS or JS changes.
  73. End-to-End tests are the set of tests that are the closest to what the user should experience when using your product. At the end of August 2023 Protractor will officially have reached the end of long term support and will transition to End of Life in September 2023. Protractor has been a popular e2e testing tool for Angular apps. However, Protractor is no longer included in new Angular projects as of Angular 12. Check out Migrating from Protractor to Cypress.
  74. Hold the Ctrl or Cmd key when click on the resource type to filter multiple resource types (e.g. CSS + Font + Image) in Devtools Network panel.
  75. You can type cal 2022 or cal june 2022 in Terminal and get the calendar right in your Terminal.
  76. Difference between 404 Not Found and 405 Method Not Allowed: 404 means the server has not found anything matching the Request-URI, which is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable. 405 means the method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response must include an Allow header containing a list of valid methods for the requested resource.
  77. On Mac you can check the clipboard to see what’s stored there by opening Finder and then choosing Edit > Show Clipboard. (Mac clipboard is only designed to hold one item at a time.)
  78. clear command or Ctrl + L to clear the terminal is implemented within Bash/Zsh. It's part of the shell environment. Certain terminal applications also implement their own shortcuts, like Cmd + K, and these application-level shortcuts can work even while the shell is busy (say you're running a dev server).
  79. Use cmd-shift-4 and then press the spacebar to screenshot the whole application window. To exclude the window's shadow from the screenshot, press and hold the Option key while you click. If you see a thumbnail in the corner of your screen, click it to edit the screenshot.
  80. Mac by default uses PNG as the format for screenshots, and the size of some screenshots is huge. Run the command defaults write com.apple.screencapture type jpg, followed by killall SystemUIServer. This will make the screenshots use JPG for the format, which will be much more lightweight.
  81. <input type="file" capture="user" accept="image/*"> has an attribute to open the camera of mobile devices to capture images. This is done with the capture attribute which can take two values: user for the front camera and environment for the back camera.
  82. For video tags <video poster="picture.png"> with the poster attribute, you can create an image which is displayed while the video is downloading, or until the user hits the play button. If this is not included, the first frame of the video will be used instead. Note that if you have a <video> with no poster attribute, you don't see a thumb on iOS. Trick! If you put #t=0.001 at the end of the src, it will. Caveat here is that it then downloads extra Byte Ranges of data from the video, so it costs bandwidth.
  83. Install es6-string-html from vscode extensions, and simply insert the comment /*html*/ before the string to enable syntax highlighting in es6 multiline strings.
  84. Use favicon.io to quickly generate your favicon from text, image, or emoji. The word favicon is short for "favorite icon" and originates from Internet Explorer’s "Favorites" feature which most modern browsers call "bookmarks". The most common favicon formats are ICO, PNG, and SVG.
  85. The most efficient way to store JSON in the URL’s query string is to use JSONCrush, so they can be shared and bookmarked easily. If used in a url you must call encodeURIComponent() to escape any special characters.
  86. There is no better way to craft multi-line terminal commands than Composer in iTerm2. Cmd + Shift + . to open a Composer, and type some multi-line command, then Shift + Return to execute.
  87. In order to increase the buffer history in iTerm2, there is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal or you can just pump up number of lines that you want to have in history in the same place.
  88. The tree program is available in Unix, as well as DOS and Windows. You can get the tree command on macOS using brew install tree. Parameter -f to print with the full path prefix for each sub-directory and file, -p prints the file type and permissions, -s prints the size of each file in bytes (-h for a human-readable format), -D with the date of the last modification time.
  89. Math.trunc() function returns the integer part of a number by removing any fractional digits. Unlike Math.floor() or Math.ceil(), it truncates (cuts off) the dot and the digits to the right of it, no matter whether the argument is a positive or negative number.
  90. CR and LF are control characters and used to mark a line break in a text file. Unix systems like Linux and macOS use LF, the line feed character (0x0A, \n), which moves the cursor down to the next line without returning to the beginning of the line. Windows, on the other hand, uses CRLF, carriage return AND line feed character (0x0D 0x0A, \r\n). It moves the cursor both down to the next line and to the beginning of that line.
  91. wc command is used to find out number of lines, word count, byte and characters count in the files specified in the file arguments. wc -l <filename> tells it to count lines. wc -w <filename> tells the number of words in each input file. ls | wc -l counts the number of files in a directory (ls does ls -1, one entry per line, if the output is a pipe.)
  92. cloc parses your code file to counts the lines of code in many programming languages.
  93. In Q3 of 2021, Chrome started to shorten the release cycle and ship a new version to the stable channel every four weeks, down from the six-week cycle. Chrome 94 was the first release on the four-week schedule.
  94. A page session lasts as long as the browser is open, and survives over page reloads and restores (same page/tab and same origin). Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
  95. The <mark> HTML element represents text which is marked or highlighted. It even comes with <mark>built-in styles</mark>. This might be used, for example, to indicate the words that matched a search operation.
  96. Project Fugu is a cross company effort to close gaps in the web's capabilities, enabling new classes of applications to run on the web. More concretely, this means adding new APIs to browsers that app developers can use to enable previously impossible use cases.
  97. say command converts input text to audible speech. Use say -v '?' to obtain a list of voices installed in the system. man say to see more usages.
  98. Both SHA256 and MD5 are hashing algorithms. They take your input data and output a 256/128-bit number. This number is a checksum. There is no encryption taking place because an infinite number of inputs can result in the same hash value, although in reality collisions are rare. Hashing is different from encryption. Whereas encryption is a two step process used to first encrypt and then decrypt a message (two-way), hashing condenses a message into an irreversible fixed-length value (one-way). By the way, encoding and encryption are also different. Encoding transforms data into another format using a scheme that is publicly available so that it can easily be reversed.
  99. You can encode any text data by using base64 in command line. Run echo hello | base64 to encode and echo aGVsbG8K | base64 -d to decode. base64 sample.txt > encoded.txt will encode the content of the input file and save the encoded text into another file, and run base64 -d encoded.txt to decode.
  100. Node.js(v16.0.0, v14.18.0) starts to support a node: protocol for built-in modules. It’s immediately clear that a built-in module is imported and there is no risk of a module in node_modules overriding the built-in module.
  101. crypto.randomUUID() is a method built into the browser (it's not a third-party package) that returns a randomly generated, 36 character long v4 UUID. It's available in Node.js 14.17+ and all major browsers.
  102. Xterm.js is a front-end component that lets applications bring fully-featured terminals to their users in the browser. It's used by popular projects such as VS Code and Hyper. Note that Xterm.js is not a terminal application.
  103. The advent of WebAssembly made it possible to write a WebAssembly-based operating system to run Node.js, entirely inside your browser. Stackblitz's @webcontainer/api is a browser-based runtime for executing Node.js applications and operating system commands. These environments are not running on remote servers. Together with Xterm.js, you can build a working terminal inside the browser. The tutorial shows how to hook up your terminal to the shell running in the WebContainer process.
  104. The difference between performance.now() and Date.now() is that Date.now() returns a timestamp in relation to the Unix epoch. JavaScript gets the time from the system clock. But since the system clock lives in our machine, it can be adjusted manually or programmatically, therefore, time precision cannot be guaranteed. In this situation, performance.now() is more reliable. It depends neither on a specific point in history nor on our system because it returns the number of milliseconds that have passed since the beginning of the document’s lifetime (the time when navigation has started in window contexts).
  105. For a long time, REST was the one and only "standard" for building APIs. But in recent years, new alternatives have emerged. In 2015, Facebook released GraphQL to the public, and in 2016 Google followed suit with the release of gRPC. In gRPC, a client application can directly call a method on a server application on a different machine as if it were a local object, making it easier for you to create distributed applications and services. gRPC has advantages in server-to-server communications. By default, gRPC uses Protocol Buffers, Google’s mature open source mechanism for serializing structured data.
  106. gRPC explicitely needs HTTP/2 support, and as gRPC requires code generation, only a set of programming languages are supported. It is currently impossible to implement the HTTP/2 gRPC spec in the browser, as there is simply no browser API with enough fine-grained control over the requests. For example, there is no way to force the use of HTTP/2, and even if there was, raw HTTP/2 frames are inaccessible in browsers. As a workaround, gRPC-Web is a slight variation of the gRPC protocol to provide a JS client library that lets you access gRPC services built in this manner from browsers.
  107. Chrome provides an option to view the Web Vitals for the current page as an overlay. You can enable the overlay via the DevTools Command Menu. Press Cmd + Shift + P, type web vitals overlay, and press Enter. Then you'll then see the LCP, FID, and CLS for the page.
  108. The DevOps Research and Assessment (DORA) team has identified four key metrics that indicate the performance of software delivery. Key metrics include: Deployment frequency (how frequently an organization releases new software), Lead time for changes (the time taken from when a change is requested or initiated to when it is deployed), Mean time to recovery (the average time it takes to recover from a failure), Change failure rate (the percentage of changes that result in a failure).
  109. Browsers doesn't natively support the displaying of WebVTT text tracks that are associated with an <audio> element; They all completely ignore any <track> content. One possible solution could be to use a <video> element to play our audio. Yep, the <video> element will also accept audio files in its <source> elements.
  110. When you deploy a new version of your SPA, users with a tab open will keep using the old SPA code. A solution is that specify the app version in each HTTP call from the UI via a x-app-version header, then validate this header on the API server. If x-app-version doesn't match the server's version, return an HTTP 400. When the UI receives a 400 status code, tell the user to reload.
  111. Though there are various ways to install Python, the one I would suggest for use in data science is the Anaconda distribution, which works similarly whether you use Windows, Linux, or Mac. The Anaconda distribution comes in two flavors: Miniconda gives you the Python interpreter itself, along with a command-line tool called conda which operates as a cross-platform package manager geared toward Python packages. Anaconda includes both Python and conda, and additionally bundles a suite of other pre-installed packages geared toward scientific computing. Any of the packages included with Anaconda can also be installed manually on top of Miniconda.
  112. When entering text, press Option + Shift + K to insert an Apple logo.
  113. system_profiler is a macOS-specific command-line utility. system_profiler SPHardwareDataType prints an overview of the hardware of the current machine, including its model name and serial number. system_profiler SPSoftwareDataType prints an overview of the software of the current machine, including the exact macOS version number.
  114. PowerShell is a cross-platform task automation solution made up of a command-line shell, a scripting language, and a configuration management framework. PowerShell runs on Windows, Linux, and macOS. PowerShell commands follow a Verb-Noun semantic with a set of parameters. For example, Get-Process will display all the running processes on your system. If you are new to PowerShell and would like to learn more, we recommend reviewing the getting started documentation.
  115. It seems weird to me that Prettier will turn <br> into <br />. In early 2000s, XHTML 1.0 became a recommendation, and proposed writing HTML in a way that was compatible with both existing HTML parsers and XML parsers (at that time there was no HTML parsing spec, on the other hand, XML has a fully defined parser, e.g. attributes require values, tags have to explicitly close). But, one of the great things about browsers is they're error-tolerant. Note that in HTML, it isn't the /> that closes the br, it's the "br". It's part of a special list of elements that can never have children, and therefore they self-close. <div /> doesn't self-close, because "div" isn't on that list. HTML5 entered the scene in 2008, and one of the major things it introduced was a parsing spec, which detailed what browsers should do when they encounter weird and invalid markup.
  116. The chrome://predictors page shows some cool stats about the characters you've typed in the omnibox and the URLs you've selected. For example, if you usually type "y", Chrome autocompletes the URL to youtube.com and you press Enter, you'll find this association in the table. There are 3 values: hit count (how often you type those characters), miss count (how often you pick a different suggestion) and confidence score equals hit_count / (hit_count + miss_count). Green entries have a 1 confidence score, which means that the text is always associated with the URL.
  117. Note that there are other browsers available on iOS like Chrome and Firefox, but due to Apple’s App Store rules every browser in the App Store is simply a UI wrapper around the Safari rendering engine and JavaScript engine (Apps that browse the web must use the appropriate WebKit framework and WebKit JavaScript.). If a bug exists on iOS Safari, it also exists in iOS Chrome, iOS Firefox, etc.
  118. WeChat QR Code scanner is a Convolutional Neural Network (CNN) based library to detect and decode QR codes. It was developed and contributed by the WeChat Computer Vision team, and integrated into OpenCV with the release 4.5.2 in the opencv-contrib package. qr-scanner-wechat is a scanner for JavaScript, based on a WebAssembly build of OpenCV and WeChat QR Code Scanner.
  119. Sometimes a bad guy may trigger your endpoints over and over again. A common way to reduce the impact and likelihood of this is to rate limit requests. This means that you only allow a certain number of requests from a given IP address within a certain time period. The most popular and well maintained library for express is express-rate-limit. One challenge with rate limiting in a production environment is if you have multiple instances of your application running behind a load balancer. In this case, you need to ensure that the rate limit is applied across all instances and not just to each individual instance. express-rate-limit allows you to do this by using a shared storage mechanism (a redis store).
  120. UnJs is a library all about universal JavaScript (zero dependency, work in node and browser and you can use anywhere). It's created out of Nuxt, creating utilities that we were using internally, but we didn't want them to be Nuxt only. Nitro, from the UnJS ecosystem, is an intuitive framework to create type-safe and performant universal web servers, with zero-config compatibility with multiple platforms. NuxtJS is built upon Nitro, which is built upon H3.
  121. Open Graph (OG) is a standard allowing developers to specify an image and other metadata to be displayed when sharing links on the web through platforms like Twitter, Facebook, Slack, and even text messages. To assist with generating dynamic OG images, you can use the @vercel/og library to compute and generate social card images using Vercel Edge Functions.
  122. monaco-editor is a browser based code editor that powers VS Code, but it's an overkill for websites that only need to show read-only codeblocks. monaco-vue enables you to use monaco-editor loaded from CDN in Vue 2&3.
  123. JSX.Element and React.ReactElement are functionally the same type. They can be used interchangeably. They represent the thing that a JSX expression creates. They can't be used to represent all the things that React can render, like strings and numbers. For that, use React.ReactNode. In everyday use, you should use React.ReactNode. You rarely need to use the more specific type of JSX.Element.
  124. If there are three setCount(count + 1) in a click event handler in React, it will only increment the count by 1, despite the three calls. React state updates are async and batched so it will re-render only once. All three setCount are looking at the state of count on the same loop, so all of them see that count is 0 and all of them change it to 1. You're just setting it to 1 three times. If it was setCount(c => c + 1) then the result is 3. When we call setCount, we aren't re-assigning a variable. We're scheduling an update.
  125. A lot of browser functionalities, like DOM manipulations (DOMParser), are not available natively in NodeJS because that is not a typical server task to access the DOM - you'll have to use an external library to do that. You can use jsdom or cheerio.
  126. The form submit() method does not trigger input validation, and there won't be a submit event. This is where requestSubmit() is useful. It acts exactly like a trigger on a submit button. The form's content is validated, and the form is submitted only if validation succeeds. It also can be canceled via event.preventDefault in a submit event handler.
  127. A .gitkeep file is a special file that you can use to add empty directories to a Git repository. Git does not track empty directories by default. People who want to track empty directories in Git have created the convention of putting files called .gitkeep in these directories. .gitkeep is just a placeholder. The file could be called anything; Git assigns no special significance to this name.
  128. The file type can be specified by the server with a Content-Type header. application/octet-stream is the most generic type, and it tells the browser that the file is just arbitrary data - at which point the only thing the browser can do is download it. When a Content-Type is not specified by the server, the browser can perform what is known as sniffing to try to guess the type by reading the file and looking for patterns.
  129. Browsers send an accept-encoding HTTP header when requesting text files, like Accept-Encoding: gzip, deflate, br. That tells the server that it understands data compressed in either Gzip, Deflate, or Brotli. Gzip has been around since 1992 and is very widely supported. However, the Brotli algorithm that was released in 2013 built by Google provides better compression and should be used whenever possible. Note that Gzip or Brotli don't help when transferring images. That's because image formats already contain compression algorithms that are optimized specifically for images.
  130. Facebook’s zStandard compression is another promising new method which aims to serve smaller payloads compared to gzip while also being faster. zStandard was added to the HTTP content encodings with an identifier of “zstd”, and support for it was added to Chrome in version 123. When considering a compression level, it’s important to balance the time it takes to compress a payload with the estimated byte savings. For example, utilizing the maximum compression level will often produce the smallest payload, but will do so at a higher computational cost.
  131. localStorage is usually limited to 5MB. lz-string was designed to fulfill the need of storing large amounts of data in localStorage, specifically on mobile devices. It started out from an LZW implementation (a universal lossless data compression algorithm). Try to use LZString.compressToUTF16() and LZString.decompressFromUTF16() to store compressed data into localStorage.
  132. BlurHash or ThumbHash is a compact representation of a placeholder for an image. The algorithm encodes your image into a short string (only 20-30 characters), ready to save in a database. When you send data to your client, you send both the URL to the image, and the BlurHash string. Your client then takes the string, and decodes it into a small image that is rendered on to a canvas while the real image is loading over the network.
  133. A labeled statement is any statement that is prefixed with an identifier. You can use a label to identify a statement, and later refer to it using a break or continue statement. For example, we have a loop1: for (let i = 0; i < 3; i++) {} with a labeled break. When break loop1 is encountered, the execution of the loop1 is terminated.
  134. The "Idle" state in Performance tab of Chrome DevTools is the time when nothing has happened (so I'm not sure why you would want to reduce it). Go to about:blank page, and get a new CPU profile. The result is probably the value for idle close to 100%. The "Idle" state should not be confused with the "Loading" state.
  135. Word Error Rate (WER) is the most common metric used today to evaluate the effectiveness of an automatic speech recognition system (ASR). WER can be defined using the formula: WER = (# of words inserted + # of words deleted + # of words substituted) / total # of words. But when a speech recognition API fails to recognize words important to your analysis, it is not good enough-no matter what the WER is.
  136. Voice activity detector (VAD) is the detection of the presence or absence of human speech, used in speech processing. vad-web provides an accurate, user-friendly VAD that runs in the browser. You can start recording audio and send segments of audio with speech to your server. Under the hood, it runs pre-trained VAD algorithm using ONNX Runtime Web (cross-platform machine-learning model accelerator).
  137. In function calls, all calculations occur using the ALU, which means that variables from memory need to be loaded into registers. As a caller, when invoking a function, you must save the current state (since the callee might overwrite certain registers) by storing register values in memory. There exists a convention between callers and callees, for example, callers save and restore registers 1-8, while callees handle registers 9-16. Understanding where parameters reside (in specific registers or the Activity Record) and where return values are stored is crucial. Each function has its own Activity Record (AR) in memory, containing information like arguments, parent addresses, caller-save registers, and local variables. Store and load operations facilitate data movement between registers and RAM.
  138. A bloom filter is a probabilistic data structure that is based on hashing. It is extremely space efficient. When testing if an element is in the bloom filter, false positives are possible. It will either say that an element is definitely not in the set or that it is possible the element is in the set.
  139. Back in 2017, Chrome 59 introduced the so-called Headless mode, which lets you run the browser without any visible UI. Headless mode is a popular choice for browser automation (UI testing, taking screenshots, creating a PDF) through projects like Puppeteer (A Node library developed by the Chrome team, which provides a high-level API to control headless/full Chrome. It can be used to crawl SPAs). Technically, it's important to know that the old Headless was a separate, alternate browser implementation that happened to be shipped as part of the same Chrome binary. It doesn't share any of the Chrome browser code. In Chrome 112, the new Headless mode (passing --headless=new flag) is available that unifies Headless and headful modes.
  140. What does 2>&1 mean? The N> syntax in Bash means to redirect a file descriptor to somewhere else. 2 is the file descriptor of stderr; 1 means stdout. So 2>&1 will redirect stderr to stdout. (& is only interpreted to mean "file descriptor" in the context of redirections.)
  141. Undici, a modern HTTP/1.1 client library for Node.js, served as the foundation for Node.js’ native fetch() implementation. Undici means eleven in Italian (1.1 -> 11 -> Eleven -> Undici). Undici is a replacement for http.request because we could not improve http.request without breaking everybody.
  142. Jina AI Reader converts any URL into Markdown content suitable for piping into an LLM, by simply adding r.jina.ai to the front of a URL to get back Markdown of that page. It's written in TypeScript and uses Puppeteer to run Readabiliy.js (extract content from web pages) and Turndown (HTML to Markdown converter) against the scraped page. Another one, by adding s.jina.ai to your query, it will call the search engine and returns top-5 results with their URLs and contents, each in clean, LLM-friendly text.
  143. Similar to Jina Reader, Firecrawl is an API service that takes a URL, crawls it, and converts it into clean markdown or structured data. They crawl all accessible subpages and give you clean data for each. Start exploring with the playground and the free plan includes 500 pages.
  144. How does ChatGPT render messages? If you take some time to disect the ChatGPT UI a bit, you’ll notice that it uses Tailwind. More specifically, the ChatGPT response component uses the prose HTML class. This class comes from the Tailwind CSS Typography Plugin which you can use to add beautiful typographic defaults to any vanilla HTML you don’t control, like HTML rendered from Markdown. It adds a new prose class that you can apply to any block of vanilla HTML content and turn it into a beautiful, well-formatted document.
  145. You can use VS Code to compare two files. Right click file 1 and “Select for compare”, then right click file 2 and “Compare with selected”. A side-by-side diff displays.
  146. Leaflet Maps are divided into a grid of small images called tiles. This allows for efficient loading and displaying of large maps. Leaflet only loads the tiles visible in the current viewport. As you move around or zoom, it requests new tiles as needed. At zoom level 0, the entire world fits in a single tile. At zoom level z, the world is divided into 2^z tiles horizontally and vertically. Leaflet also supports a wide range of tile providers like OpenStreetMap and Mapbox.
  147. Circuit breaker is a design pattern to create resilient microservices by limiting the impact of service failures and latencies. You wrap a protected function call in a circuit breaker object, which monitors for failures. Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all.
  148. navigator.getBattery().then(status => console.table(status)) provides information about the system's battery. This feature is available only in secure contexts (HTTPS) and in some supporting browsers (Chrome/Edge).
  149. When a page is loaded as a result of a POST request, the browser retains the request data, which can cause the data to be resent if the user refreshes the page. A common solution is to use the POST-Redirect-GET (PRG) pattern. After a POST request is processed on the server, instead of returning the same page, the server can redirect the user to a new page (typically using a 302 redirect). This way, when the user refreshes the page, the browser only resubmits a GET request, avoiding resubmission of the POST data.