title: "TIL" description: "" added: "" top: true
^
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.__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.)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.path.resolve('/a', '/b', 'c')
returns: /b/c
path.join('/a', '/b', 'c')
returns: /a/b/c
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
returns: /foo/bar/baz/asdf
github.com
with github.githistory.xyz
(i.e. https://github.githistory.xyz/kexiZeroing/FE-Learning-notes/blob/master/README.md)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.Cmd + K
to open the GitHub command palette to quickly navigate, search projects and try other commands. There is a related React component cmdk.Cmd + Shift + .
toggles hidden files in Mac.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.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)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.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.data:text/html,<html contenteditable>
. The world smallest office suite is worth to check out.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.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.npm install -g tldr
which simplify the man pages
with practical examples, e.g. try to run tldr tar
or tldr git branch
.m
to display all the available commands.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)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.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.setTimeout(console.log, 1000, 'hello');
window.scroll({top: 100, left: 100, behavior: 'smooth'});
or setting in CSS html { scroll-behavior: smooth; }
const item = {... true && {bar: 'bar'}, ... false && {falsy: 'falsy'}};
, and the item will be {bar: "bar"}
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.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.=
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
.$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.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.set -e
at the beginning.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.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.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.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
.@angular/compiler
code in our production bundle anymore.<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.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.)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.$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()
.document.designMode = 'on'
in devtools console to make your whole website editable, which great to test different texts.$
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.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.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.<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./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
.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.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.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.)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.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.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.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
.dig
to determine the AAAA record associated with a domain name dig AAAA example.com
.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.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.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.Break on
sub menu -> Choose the type of breakpoint (subtree modification, attribute modification, node removal)-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.URL.createObjectURL()
to create an object URL then setting src
to that URL. Now you can just set srcObject
to the MediaStream directly.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.npm init
) is essentially the same as MIT but without the clauses that would be considered extraneous.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.Ctrl
or Cmd
key when click on the resource type to filter multiple resource types (e.g. CSS + Font + Image) in Devtools Network panel.cal 2022
or cal june 2022
in Terminal and get the calendar right in your Terminal.Allow
header containing a list of valid methods for the requested resource.Edit > Show Clipboard
. (Mac clipboard is only designed to hold one item at a time.)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).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.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.<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.<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.es6-string-html
from vscode extensions, and simply insert the comment /*html*/
before the string to enable syntax highlighting in es6 multiline strings.encodeURIComponent()
to escape any special characters.Cmd + Shift + .
to open a Composer, and type some multi-line command, then Shift + Return
to execute.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.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.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.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.)sessionStorage
for each tab/window.<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.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.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.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.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.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).Cmd + Shift + P
, type web vitals overlay
, and press Enter. Then you'll then see the LCP, FID, and CLS for the page.<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.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.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.Option + Shift + K
to insert an Apple logo.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.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.<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.hit_count / (hit_count + miss_count)
. Green entries have a 1 confidence score, which means that the text is always associated with the URL.express-rate-limit
allows you to do this by using a shared storage mechanism (a redis store).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
.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.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.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..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.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.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.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.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.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.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.--headless=new
flag) is available that unifies Headless and headful modes.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.)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.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.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.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.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).--app='https://app.example'
parameter with Chromium-based browsers to launch a website in "app mode". This mode launches the website without the typical browser interface, such as tabs, the address bar, or navigation buttons, making the website look and feel more like a standalone application. (e.g., in macOS /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --app='https://example.com'
)src/artifact-component.tsx
file and have them rendered instantly.networkQuality
in Terminal. For more information about this command, enter man networkQuality
. The results use a measure called Round-trips Per Minute (RPM). The RPM is the number of sequential round-trips, or transactions, a network can do in one minute under normal working conditions.curl ipinfo.io
.