Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

Why “Yarn 2” is actually Yarn 3

What do we know as Yarn 2?

It’s the modern version of Yarn that comes with important upgrades to the package manager including PNMP-style symlinks, and an innovative new Plug ‘n’ Play module installation method for much-reduced project sizes and rapid installations.

But after migrating from Yarn 1, you’ll find something interesting, as I did – the thing widely known as Yarn 2 is actually… version 3?

After migrating to "Yarn 2" and checking the version, it was shown to be version 3.

Why is “Yarn 2” using version 3?

It’s because Yarn 1 served as the initial codebase which was completely overhauled in the Yarn v2.0 (the actual version 2), enhancing its efficiency and effectiveness, with its launch taking place in January 2020. As time moved on, the introduction of a fresh major, Yarn v3.0, happened, thankfully without the need for another codebase rewrite. The upcoming major update is expected to be Yarn v4.0, and so on.

Despite the historical tendency of releasing few major updates, there was a growing trend among some individuals to label everything that used the new codebase as “Yarn 2”, which includes Yarn 2.x versions and future ones such as 3.x. This, however, was a misinterpretation as “Yarn 2” strictly refers to the 2.x versions. A more accurate way to reference the new codebase would be “Yarn 2+” or “Yarn Berry” – a codename that the team selected for the new codebase when they started developing it.

As once stated by one of the maintainers in a related GitHub discussion:

Some people have started to colloquially call “Yarn 2” everything using this new codebase, so Yarn 2.x and beyond (including 3.x). This is incorrect though (“Yarn 2” is really just 2.x), and a better term to refer to the new codebase would be Yarn 2+, or Yarn Berry (which is the codename I picked for the new codebase when I started working on it).

arcanis, a Yarn maintainer

How to migrate from Yarn v1 to Yarn Berry

A Yarn Berry installation in progress.
A Yarn Berry installation in progress.

If you’re still using Yarn version 1 – or worse, NPM – you’re missing out.

The new Yarn is loaded with a sizable number of upgrades that will significantly improve your developer experience when you start using it. These range from notable improvements in stability, flexibility, and extensibility, to brand new features, like Constraints.

You can migrate from Yarn v1 to Yarn Berry in 7 easy steps:

  1. Make sure you’re using Node version 18+.
  2. Run corepack enable to activate Corepack.
  3. Navigate to your project directory.
  4. Run yarn set version berry.
  5. Convert your .npmrc and .yarnrc files into .yarnrc.yml (as explained here).
  6. Run yarn install to migrate the lockfile.
  7. Commit all changes.

In case you experience any issues due to breaking changes, this official Yarn Berry migration guide should help.

Final thoughts

The Yarn versioning saga teaches us an important lesson: terminology matters.

What many of us dub as “Yarn 2” is actually “Yarn 2+” or “Yarn Berry”, the game-changing codebase. This misnomer emphasizes our need to stay current, not just with evolving tools and features, but with their rightful names as well. After all, how we understand and converse about these improvements shapes our effectiveness and fluency as developers.

How to quickly get the height or width of an element in React

To get the height or width of an element in React, use the useRef, useEffect, and useState hooks to access the element’s offsetWidth or offsetHeight property:

JavaScript
import React, { useEffect, useState, useRef } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); const elementRef = useRef(null); useEffect(() => { setWidth(elementRef.current.offsetWidth); setHeight(elementRef.current.offsetHeight); }, []); return ( <div ref={elementRef} style={{ width: '50%', height: '50%', border: '1px solid black' }} > <p>Coding Beauty</p> <p>{`Element size: (${width}, ${height})`}</p> </div> ); } export default function App() { return ( <div> <ExampleComponent /> </div> ); }
The height and width of the element is displayed with React.

useEffect() runs after the component mounts or re-renders, but useLayoutEffect() runs before. They both have a dependency array that triggers them when any of those dependencies change.

We create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We use useState() to create a state that we update when useEffect() gets called. This update makes the element’s width and height display on the page.

Get height and width of element with clientHeight and clientWidth

You can also get an element’s height and width in React with clientHeight and clientWidth. Unlike offsetWidth, it includes padding but excludes borders and scrollbars.

JavaScript
import React, { useRef, useState, useEffect } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); const elementRef = useRef(null); useEffect(() => { setWidth(elementRef.current.clientWidth); setHeight(elementRef.current.clientHeight); }, []); return ( <div ref={elementRef} style={{ width: '50%', height: '50%' }}> <p>Coding Beauty</p> <p> <b>{`Element size: (${width}, ${height})`}</b> </p> </div> ); } export default function App() { return ( <div> <ExampleComponent /> </div> ); }
Getting the size of an element in React with clientWidth and clientHeight.

Get height and width of element dynamically

You can get the height and width of an element dynamically, which means the height and width updates on window resize.

We do this with a resize event listener:

JavaScript
import React, { useEffect, useState, useRef } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); const elementRef = useRef(null); useEffect(() => { const handleResize = () => { setWidth(elementRef.current.offsetWidth); setHeight(elementRef.current.offsetHeight); }; handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }, []); return ( <div ref={elementRef} style={{ width: '50%', height: '50%' }}> <p>Getting element width dynamically</p> <p><b>{`Element size: (${width}, ${height})`}</b></p> </div> ); } export default function App() { return ( <div> <ExampleComponent /> </div> ); }

We call addEventListener() in useEffect() to set the resize event listener on the element before it renders on the screen.

The resize event listener is called whenever the user resizes the window. In the listener, we update the state that stores the element’s width and height, and this causes a re-render.

We call removeEventListener() in useEffect‘s clean-up function to stop listening for resize events when the component is unmounted or when the dependencies change to prevent memory leaks and unintended side effects.

Get element height and width before render in React

To get the width and height of an element before render in React, we can combine two React hooks: useRef and useLayoutEffect.

JavaScript
import React, { useRef, useLayoutEffect, useState } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const [height, setHeight] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { setWidth(elementRef.current.offsetWidth); setHeight(elementRef.current.offsetHeight); }, []); return ( <div style={{ width: '50%', height: '50%' }}> <p>Coding Beauty</p> <div ref={elementRef}> Element size: ({width}, {height}) </div> </div> ); } export default function App() { return ( <div> <ExampleComponent /> </div> ); }

So the difference between “before render” and “after render” is useLayoutEffect() and useEffect().

useLayoutEffect() works just like useEffect(), but the key difference is that it fires before the browser repaints the screen – before React renders the component.

We pass an empty dependencies array to useLayoutEffect() to make sure it only gets called once.

Here we create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We do use useState() though, to create a state that we update when useLayoutEffect() gets called. So calling setWidth() will cause the component to be re-rendered.

To get the actual width and height, we use the offsetWidth and offsetHeight properties, which include borders, padding, and any scrollbars.

Key takeaways

  1. To get the height or width of an element in React, combine the useRef, useEffect, and useState hooks to get the value of offsetWidth and offsetHeight.
  2. clientWidth and clientHeight are similar to offsetWidth and offsetHeight, but they include padding and exclude borders and scrollbars.
  3. To get the dimensions of the element dynamically, create a window resize event listener to automatically update the size when the user resizes the browser window.
  4. To get the size of the element before render, replace useEffect with useLayoutEffect.

[SOLVED] 0308010C:digital envelope routines::unsupported

The error:0308010C:digital envelope routines::unsupported error happens in Node.js when a JavaScript module still uses a flawed OpenSSL version that is incompatible with the version Node.js uses.

The "error:0308010C:digital envelope routines::unsupported" error occurring in Vue.js.
The error:0308010C:digital envelope routines::unsupported error occurring.

To fix it, downgrade to Node.js v16.13.0, or use the npm audit fix --force command to upgrade your packages to versions that use the updated OpenSSL version.

Why does the error:0308010C:digital envelope routines::unsupported error occur in Node.js?

In Node.js v17, the Node.js team patched an OpenSSL security vulnerability. This fix introduced a breaking change; if you try to use OpenSSL in Node.js v17 or later versions without also updating those modules that use previous OpenSSL versions, you’ll get this error.

And you’ll get it the next time Node.js is updated to use a newer OpenSSL version with breaking changes and you haven’t updated the OpenSSL-dependent libraries.

Fix: Upgrade NPM packages

To fix the error:0308010C:digital envelope routines::unsupported error, update the Node.js packages causing the error to the latest version.

Run npm audit fix to fix vulnerabilities

You can run the npm audit fix command to identify those packages using the outdated OpenSSL version and fix them automatically.

Shell
npm audit fix

npm audit fix reviews the project’s dependency tree to identify packages that have known vulnerabilities, and attempts to upgrade and/or fix the vulnerable dependencies to a safe version.

npm audit fix --force

If you want to install semver major updates to vulnerable packages, you can use the --force option. 

Shell
npm audit fix --force

Be cautious with this option: it could potentially break your project.

yarn-audit-fix

If you’re a Yarn user, you can use the yarn-audit-fix package to do what npm audit fix does.

Upgrade Webpack to v5

If you’re using Webpack directly to bundle your files, you can upgrade it to version v5 – specifically, v5.61.0 – to fix the error:0308010C:digital envelope routines::unsupported error.

Shell
npm i webpack@latest # Yarn yarn add webpack@latest

If instead, you’re using a tool like Create React App and the Vue CLI that uses Webpack internally, you’ll upgrade the tool to a version that doesn’t have this error.

Fix for Create React App: Upgrade react-scripts to v5

If you’re using Create React App then you can fix the error:0308010C:digital envelope routines::unsupported error by upgrading react-scripts to version 5, which comes with the newer Webpack version 5.

Install version 5 or later with this command:

Shell
npm i react-scripts@latest # Yarn yarn add react-scripts@latest

Fix for Vue CLI: Upgrade to v5

Similarly for the Vue CLI, you can fix the error:0308010C:digital envelope routines::unsupported error by upgrading the Vue CLI to version 5 which also comes with the newer Webpack version 5.

Install Vue CLI version 5 or later with this command:

Shell
npm update -g @vue/cli # OR yarn global upgrade --latest @vue/cli

More info on how to upgrade the Vue CLI here.

Fix: Use --openssl-legacy-provider option

To fix the error:0308010C:digital envelope routines::unsupported error in Node.js, you can also use the --openssl-legacy-provider option when running the script.

This solution is more of a hack though: it leaves your app open to security threats.

The --openssl-legacy-provider option is only available in Node version 17 or later.

Run with script

So for the start script, you’ll use this command:

Shell
export NODE_OPTIONS=--openssl-legacy-provider && npm run start # Windows set NODE_OPTIONS=--openssl-legacy-provider && npm run start

Modify script

You can also set this directly in the script to avoid needless repetition.

On Linux/Mac:

JSON
{ ... "scripts": { "start": "export NODE_OPTIONS=--openssl-legacy-provider && webpack serve", "build": "webpack --mode production" } ... }

On Windows:

JSON
{ ... "scripts": { "start": "set NODE_OPTIONS=--openssl-legacy-provider && node .", "build": "set NODE_OPTIONS=--openssl-legacy-provider && node build.js" } ... }

Make sure the script is cross-platform

But now the scripts aren’t cross-platform.

They’ll obviously be problematic when collaborating and team members use other operating systems. What do we do? We install the cross-env NPM module and run the script with it.

Shell
npm i cross-env # Yarn yarn add cross-env
JSON
{ ... "scripts": { "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider webpack .", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider node build.js" }, "devDependencies": { "cross-env": "^7.0.3" } ... }

Now the script runs successfully on every platform.

Fix for Vue CLI

So to fix the error:0308010C:digital envelope routines::unsupported error when using Vue with the Vue CLI, install the cross-env module and set the --openssl-legacy-provider option:

JSON
{ ... "scripts": { "serve": "cross-env NODE_OPTIONS=--openssl-legacy-provider vue-cli-service serve", ... }, "devDependencies": { "cross-env": "^7.0.3" ... } ... }

Fix for Create React App

And to fix the error:0308010C:digital envelope routines::unsupported error when using React with Create React App, install the cross-env module and set the --openssl-legacy-provider option.

JSON
{ ... "scripts": { "serve": "cross-env NODE_OPTIONS=--openssl-legacy-provider ", ... }, "devDependencies": { "cross-env": "^7.0.3" ... } ... }

Fix: Downgrade to Node.js v16.13.0

To fix the error:0308010C:digital envelope routines::unsupported error in Node.js, downgrade your Node.js version to 16.13.0.

This solution is more of a hack though, as it leaves your app open to security threats.

Install from the official website

Use this official link to download Node.js v16.13.0.

Install with Chocolatey

If you’re using Chocolatey, Node.js is available as the nodejs package, meaning you can easily install it in a terminal using the following command.

Shell
# Use current LTS version choco install nodejs --version=18.5.0

Install with nvm

If you’re using nvm or nvm-windows, use these commands to quickly install and switch to Node.js v16.13.0.

Shell
nvm install 16.13.0 nvm use 16.13.0

How to Quickly Reveal the Current File in Explorer in VS Code

You either want to reveal the current file in the VS Code Explorer sidebar view or in your OS file manager. We cover both in this article.

Reveal current file in Explorer view in VS Code

To reveal the current file in the Explorer view of Visual Studio Code, use the Reveal Active File in Explorer View command, accessible from the Command Palette.

Revealing the active file in the VS Code Explorer view.

Why is it useful to reveal the current file in the VS Code Explorer view?

When working on a project with numerous files and directories, it can sometimes be challenging to remember the exact location of a specific file. Revealing the current file in the VS Code Explorer view allows you to quickly locate the file’s position within the project structure.

  1. Context: This is particularly useful when you want to gain a broader context of where the file is located in relation to other files and folders.
  2. Navigation: And you can easily navigate to these related files.
  3. File management: VS Code’s Explorer view provides file management capabilities, such as renaming, moving, and deleting files. If you’re currently editing a file and you want to perform a management action on it, revealing the file in the Explorer view makes it easier to perform these actions without having to manually navigate through the directory structure.
  4. Version control: If your project is under version control like Git, revealing the current file in the Explorer view can help you understand the file’s status in the context of version control. You can see if the file has been modified, staged, or is part of a particular branch, which can aid in your development workflow.
  5. Collaboration: When working on a project with others, revealing the current file can help your team members easily find and access the same file you’re working on. This is especially useful if you’re discussing a specific file in a conversation or during a code review.

Use the Reveal in File Explorer View command

To reveal the current file in the Explorer view in VS Code, run the Reveal Active File in Explorer View command.

Reveal the active file in the VS Code Explorer view.

In VS Code, we have commands – defined actions that carry our various operations in the editor.

We can easily run a command with the Command Palette, which we can access with these keyboard shortcuts:

  • Windows / LinuxCtrl + Shit + P
  • Mac: Command + Shift + P

Reveal current file in Explorer with active editor context menu

You can also reveal the current file in the VS Code Explorer sidebar with the Reveal in Explorer View option in the context menu that shows up when you right-click the filename at the top.

Reveal the current file with the VS Code active editor context menu.

This item is also there in the context menu that shows when you right-click the file in the Source Control view.

This Reveal in Explorer View item is in the Source Control view context menu.

Reveal current file in Windows File Explorer / Mac Finder

To reveal the current file in your operating system’s file manager, use the Reveal in File Explorer command, accessible from the Command Palette.

The Reveal in File Explorer command in VS Code.

By the way, if you’re on Windows 11 and you’re dealing with File Explorer clutter, this tiny utility called WinENFET can help, by automatically opening File Explorer in a new tab, instead of a new window.

Why is it useful to reveal the current file in File Explorer/Finder?

When managing a project that includes many files and folders, it can occasionally become difficult to recall the precise location of a particular file. By displaying the current file in your operating system’s file manager, you can swiftly identify the file’s place within the project hierarchy.

This is useful for several reasons:

  1. Context: Helps you understand and navigate your project’s larger file hierarchy. This is especially helpful in large projects with complex file structures.
  2. External operations: You can perform actions not available in VS Code, like viewing file properties (creation date, size, etc.) or file permissions.
  3. Data transfer: Allows you to quickly locate the path for file transfers. If you need to send the file as an email attachment or upload it to a server, you can quickly find it in the operating system’s file manager.
  4. Easy access: If you’re working with a file in VS Code and you want to quickly open it in another application, revealing the file in the file manager makes this easy.
  5. Collaboration: If you’re working with a team, it’s easy to reveal the file in the file manager, zip it, and send it to team members as needed.

Use the Reveal in File Explorer command

To reveal the current file in your OS’s file manager in VS Code, run the Reveal in File Explorer command.

The Reveal in File Explorer command in VS Code.

In VS Code, we have commands: defined actions that carry out various operations in the editor.

We can easily run a command with the Command Palette, which we can access with these keyboard shortcuts:

  • Windows / Linux: Ctrl + Shit + P
  • Mac: Command + Shift + P

Reveal current file in File Explorer with active editor context menu

Alternatively, you can reveal the current file in your OS’s file manager with the Reveal in File Explorer option in the context menu that shows up when you right-click the filename at the top.

Revealing the current file in File Explorer/Finder from VS Code.

Set custom keyboard shortcuts for commands in VS Code

To set a custom keyboard shortcut for the Reveal in File Explorer or Reveal Active File in Explorer View command, change the keybinding for the command in the Keyboard Shortcuts page.

To get this page, you can click the Keyboard Shortcuts item on the Manage popup shown below or use the shortcut next to the text (Ctrl + K, Ctrl + S here).

Opening the Keyboard Shortcuts page from the Manage popup in VS Code.

Once you get there, search for the Reveal in File Explorer or Reveal Active File in Explorer View command in the search bar.

Searching for the Reveal in File Explorer keyboard shortcut.

Then double-click the command, type a new keyboard shortcut, and press the Enter key to carry out the change.

Changing the Reveal in File Explorer keyboard shortcut in VS Code.

Key takeaways

  • To reveal a file in the VS Code Explorer view, run the Reveal Active File in Explorer View command. You can do this with the Command Palette, or by setting a custom keyboard shortcut.
  • To reveal a file in your OS file manager (Windows File Explorer, Mac Finder, etc.), run the Reveal in File Explorer command. You can also do this with the Command Palette, or by setting a custom keyboard shortcut.
  • To set a keyboard shortcut for a command in VS Code, open the Keyboard Shortcuts page, select the command, type the new short, and confirm with Enter.

How to quickly get the union of two Sets in JavaScript

To get the union of two Sets in JavaScript, convert the sets to arrays and merge them, then create a Set from the merged array, i.e., new Set([...set1, ...set2]).

For example:

JavaScript
function getUnion(set1, set2) { return new Set([...arr1, ...arr2]); } const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([3, 4, 5, 6]); const union = getUnion(set1, set2); console.log(union); // Set(6) { 1, 2, 3, 4, 5, 6 }

Set() constructor

The Set() constructor creates a new Set object from an iterable like an array. As a Set can only contain unique values, it removes any possible duplicates that may be in the array it receives.

JavaScript
const set = new Set([1, 1, 2, 3, 3, 4]); console.log(set); // Set(4) [1, 2, 3, 4]

Spread syntax (...)

The array we pass to Set() is a merge of two arrays that represent the two Sets. The spread syntax (...) unpacks the value of each Set into the array.

JavaScript
const array1 = [10, 20, 30]; const array2 = [40, 50, 60]; const mergedArray = [...array1, ...array2]; console.log(mergedArray);

Use Array concat() to merge arrays

If you like, you can use the Array concat() method to join the arrays. Here the spread syntax only converts the Sets to arrays.

JavaScript
function getUnion(set1, set2) { // Using Array concat() in place of spread syntax return new Set([...set1].concat([...set2])); } const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([3, 4, 5, 6]); const union = getUnion(set1, set2); console.log(union); // Set(6) { 1, 2, 3, 4, 5, 6 }

Use Array from() to convert Set to array

You can use the Array from() method in place of the spread syntax (...) to convert the Sets to arrays before merging them:

JavaScript
function getUnion(set1, set2) { // Using Array concat() in place of spread syntax return new Set(Array.from(set1).concat(Array.from(arr2)); } const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([3, 4, 5, 6]); const union = getUnion(set1, set2); console.log(union); // Set(6) { 1, 2, 3, 4, 5, 6 }

We can use a similar approach to easily get the union of two arrays in JavaScript.

Get union of two arrays in JavaScript

To get the union of two arrays in JavaScript, merge the arrays, create a new Set object from the merged result to remove the duplicates, then convert it back to an array, i.e., Array.from(new Set([...arr1, ...arr2])).

For example:

JavaScript
function getUnion(arr1, arr2) { return Array.from(new Set([...arr1, ...arr2])); } const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const union = getUnion(array1, array2); // [1, 2, 3, 4, 5, 6, 7, 8] console.log(union);

Key takeaways

  • To get the union of two Sets in JavaScript, convert the Sets to arrays, merge them, and convert the merged array back to a Set object, i.e., new Set([...set1, ...set2]).
  • You can get the union of two arrays in JavaScript in a similar way, i.e., [...new Set([...arr1, ...arr2])].

How to quickly get the union of two arrays in JavaScript

To get the union of two arrays in JavaScript, merge the arrays, create a new Set object from the merged result to remove the duplicates, then convert it back to an array, i.e., Array.from(new Set([...arr1, ...arr2])).

For example:

JavaScript
function getUnion(arr1, arr2) { return Array.from(new Set([...arr1, ...arr2])); } const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const union = getUnion(array1, array2); // [1, 2, 3, 4, 5, 6, 7, 8] console.log(union);

Array.from() method

The Array from() method converts Sets and other iterable objects to arrays.

JavaScript
const set = new Set(['Paul', 'John', 'George', 'Ringo']); const arr = Array.from(exampleSet); console.log(arr); // ['Paul', 'John', 'George', 'Ringo'] const map = new Map(); map.set('Bob', 'Marley'); map.set('Mick', 'Jagger'); let arr2 = Array.from(map); console.log(exampleArray2); // [ ['Bob', 'Marley'], ['Mick', 'Jagger'] ]

Set() constructor

We create these sets with the Set constructor, which can only contain unique values, so it removes any possible duplicates that may be in the array it receives.

JavaScript
const set = new Set([1, 1, 2, 3, 3, 4]); console.log(Array.from(set)); // [1, 2, 3, 4]

Spread syntax (...)

To pass this array to the Set() constructor, we use the spread syntax (...) to merge the two arrays together. The spread syntax unpacks the value of each array into another array:

JavaScript
const array1 = [10, 20, 30]; const array2 = [40, 50, 60]; const mergedArray = [...array1, ...array2]; console.log(mergedArray);

Use Array concat() to merge arrays for Set()

We could use the Array concat() method in place of the spread syntax:

JavaScript
function getUnion(arr1, arr2) { return Array.from(new Set(arr1.concat(arr2))); } const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const union = getUnion(array1, array2); // [1, 2, 3, 4, 5, 6, 7, 8] console.log(union);

Use Array from() to convert Set back to array

And we could use this spread syntax to replace the Array from(), although this may make the code a bit less readable:

JavaScript
function getUnion(arr1, arr2) { return [...new Set([...arr1, ...arr2])]; } const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const union = getUnion(array1, array2); // [1, 2, 3, 4, 5, 6, 7, 8] console.log(union);

We can use the same principles to easily get the union of two sets in JavaScript.

Get union of two sets in JavaScript

To get the union of two sets in JavaScript, convert the sets to arrays and merge them, then create a Set from the results of the merge.

For example:

JavaScript
function getUnion(set1, set2) { return new Set([...set1, ...set2]); } const set1 = new Set(['a', 'b', 'c', 'd']); const set2 = new Set(['c', 'd', 'e', 'f']); const union = getUnion(set1, set2); console.log(union); // Set(6) { 'a', 'b', 'c', 'd', 'e', 'f' }

Key takeaways

  • To get the union of two arrays in JavaScript, create a new Set object from the merge of the two arrays, then convert this Set object to an array again, i.e., Array.from(new Set(arr1.concat(arr2))).
  • We can do a similar thing to get the union of two sets, i.e., new Set([...set1, ...set2]).

How to quickly fix the ERR_OSSL_EVP_UNSUPPORTED error in Node.js

The ERR_OSSL_EVP_UNSUPPORTED error happens in Node.js when a JavaScript module still uses a flawed OpenSSL version that is incompatible with the version Node.js uses.

The ERR_OSSL_EVP_UNSUPPORTED error occurring.
The ERR_OSSL_EVP_UNSUPPORTED error occurring.

To fix it, downgrade to Node.js v16.13.0, or use the npm audit fix --force command to upgrade your packages to versions that use the updated OpenSSL version.

Why does the ERR_OSSL_EVP_UNSUPPORTED error occur in Node.js?

In Node.js v17, the Node.js team patched an OpenSSL security vulnerability. This fix introduced a breaking change; if you try to use OpenSSL in Node.js v17 or later versions without simultaneously updating those modules that use previous OpenSSL versions, you’ll get this error.

And you’ll get it the next time Node.js updates to use a newer OpenSSL version with breaking changes and you haven’t updated the OpenSSL-dependent libraries.

Fix: upgrade NPM packages

To fix the ERR_OSSL_EVP_UNSUPPORTED error, update the Node.js packages causing the error to the latest version.

Run npm audit fix to fix vulnerabilities

You can run the npm audit fix command to identify those packages using the outdated OpenSSL version and fix them automatically.

Shell
npm audit fix

npm audit fix reviews the project’s dependency tree to identify packages that have known vulnerabilities, and attempts to upgrade and/or fix the vulnerable dependencies to a safe version.

npm audit fix --force

If you want to install semver major updates to vulnerable packages, you can use the --force option. 

Shell
npm audit fix --force

Be cautious with this option as it could potentially break your project.

yarn-audit-fix

If you’re a Yarn user, you can use the yarn-audit-fix package to do what npm audit fix does.

Upgrade Webpack to v5

If you’re using Webpack directly to bundle your files, you can upgrade it to version v5 – specifically, v5.61.0 – to fix the ERR_OSSL_EVP_UNSUPPORTED error.

Shell
npm i webpack@latest # Yarn yarn add webpack@latest

If instead, you’re using a tool like Create React App and the Vue CLI that use Webpack internally, you’ll upgrade the tool to a version that doesn’t have this error.

Fix for Create React App: Upgrade react-scripts to v5

If you’re using Create React App then you can fix the ERR_OSSL_EVP_UNSUPPORTED error by upgrading react-scripts to version 5, which comes with the newer Webpack version 5.

Install version 5 or later with this command:

Shell
npm i react-scripts@latest # Yarn yarn add react-scripts@latest

Fix for Vue CLI: Upgrade to v5

Similarly for the Vue CLI, you can fix the ERR_OSSL_EVP_UNSUPPORTED error by upgrading the Vue CLI to version 5 which also comes with the newer Webpack version 5.

Install Vue CLI version 5 or later with this command:

Shell
npm update -g @vue/cli # OR yarn global upgrade --latest @vue/cli

More info on how to upgrade the Vue CLI here.

Fix: Use --openssl-legacy-provider option

To fix the ERR_OSSL_EVP_UNSUPPORTED error in Node.js, you can also use the --openssl-legacy-provider option when running the script.

This solution is more of a hack though, as it leaves your app open to security threats.

The --openssl-legacy-provider option is only available in Node version 17 or later.

Run with script

So for the start script, you’ll use this command:

Shell
export NODE_OPTIONS=--openssl-legacy-provider && npm run start # Windows set NODE_OPTIONS=--openssl-legacy-provider && npm run start

Modify script

You can also set this directly in the script to avoid needless repetition.

On Linux/Mac:

JSON
{ ... "scripts": { "start": "export NODE_OPTIONS=--openssl-legacy-provider && webpack serve", "build": "webpack --mode production" } ... }

On Windows:

JSON
{ ... "scripts": { "start": "set NODE_OPTIONS=--openssl-legacy-provider && node .", "build": "set NODE_OPTIONS=--openssl-legacy-provider && node build.js" } ... }

Make sure the script is cross-platform

But now the scripts aren’t cross-platform.

They’ll obviously be problematic when collaborating and team members use other operating systems. What do we do? We install the cross-env NPM module and run the script with it.

Shell
npm i cross-env # Yarn yarn add cross-env
JSON
{ ... "scripts": { "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider webpack .", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider node build.js" }, "devDependencies": { "cross-env": "^7.0.3" } ... }

Now the script runs successfully on every platform.

Fix for Vue CLI

So to fix the ERR_OSSL_EVP_UNSUPPORTED error when using Vue with the Vue CLI, install the cross-env module and set the --openssl-legacy-provider option:

JSON
{ ... "scripts": { "serve": "cross-env NODE_OPTIONS=--openssl-legacy-provider vue-cli-service serve", ... }, "devDependencies": { "cross-env": "^7.0.3" ... } ... }

Fix for Create React App

And to fix the ERR_OSSL_EVP_UNSUPPORTED error when using React with Create React App, install the cross-env module and set the --openssl-legacy-provider option.

JSON
{ ... "scripts": { "serve": "cross-env NODE_OPTIONS=--openssl-legacy-provider ", ... }, "devDependencies": { "cross-env": "^7.0.3" ... } ... }

Fix: Downgrade to Node.js v16.13.0

To fix the ERR_OSSL_EVP_UNSUPPORTED error in Node.js, downgrade your Node.js version to 16.13.0.

This solution is more of a hack though, as it leaves your app open to security threats.

Install from official website

Use this official link to download Node.js v16.13.0.

Install with Chocolatey

If you’re using Chocolatey, Node.js is available as the nodejs package, meaning you can easily install it in a terminal using the following command.

Shell
# Use current LTS version choco install nodejs --version=18.5.0

Install with nvm

If you’re using nvm or nvm-windows, use these commands to quickly install and switch to Node.js v16.13.0.

Shell
nvm install 16.13.0 nvm use 16.13.0

Key takeaways

  • The ERR_OSSL_EVP_UNSUPPORTED error in Node.js occurs when a JavaScript module uses an outdated OpenSSL version that is incompatible with the current Node version. This typically happens when Node.js v17 or later versions are used without updating the modules that use previous OpenSSL versions.
  • To fix this error, you can:
    • Downgrade to Node.js v16.13.0.
    • Use the npm audit fix --force or yarn-audit-fix command to upgrade your packages to versions that use the updated OpenSSL version.
  • If you’re using Webpack, you can upgrade it to version v5.61.0 to fix the error. For Create React App and Vue CLI, you can upgrade them to v5.
  • Another way to fix the error is to use the --openssl-legacy-provider option when running the script. However, this solution leaves your app open to security threats and is only available in Node version 17 or later.
  • Downgrading to Node.js v16.13.0 is another way to fix the error. However, this solution also leaves your app open to security threats. You can install this version from the official website, or use Chocolatey, nvm, or nvm-windows to install and switch to this version.

Fine-tuning for OpenAI’s GPT-3.5 Turbo model is finally here

Some great news lately for AI developers from OpenAI.

Finally, you can now fine-tune the GPT-3.5 Turbo model using your own data. This gives you the ability to create customized versions of the OpenAI model that perform incredibly well at specific tasks and give responses in a customized format and tone, perfect for your use case.

For example, we can use fine-tuning to ensure that our model always responds in a JSON format, containing Spanish, with a friendly, informal tone. Or we could make a model that only gives one out of a finite set of responses, e.g., rating customer reviews as critical, positive, or neutral, according to how *we* define these terms.

As stated by OpenAI, early testers have successfully used fine-tuning in various areas, such as being able to:

  • Make the model output results in a more consistent and reliable format.
  • Match a specific brand’s style and messaging.
  • Improve how well the model follows instructions.

The company also claims that fine-tuned GPT-3.5 Turbo models can match and even exceed the capabilities of base GPT-4 for certain tasks.

Before now, fine-tuning was only possible with weaker, costlier GPT-3 models, like davinci-002 and babbage-002. Providing custom data for a GPT-3.5 Turbo model was only possible with techniques like few-shot prompting and vector embedding.

OpenAI also assures that any data used for fine-tuning any of their models belongs to the customer, and then don’t use it to train their models.

What is GPT-3.5 Turbo, anyway?

Launched earlier this year, GPT-3.5 Turbo is a model range that OpenAI introduced, stating that it is perfect for applications that do not solely focus on chat. It boasts the capability to manage 4,000 tokens at once, a figure that is twice the capacity of the preceding model. The company highlighted that preliminary users successfully shortened their prompts by 90% after applying fine-tuning on the GPT-3.5 Turbo model.

What can I use GPT-3.5 Turbo fine-tuning for?

  • Customer service automation: We can use a fine-tuned GPT model to make virtual customer service agents or chatbots that deliver responses in line with the brand’s tone and messaging.
  • Content generation: The model can be used for generating marketing content, blog posts, or social media posts. The fine-tuning would allow the model to generate content in a brand-specific style according to prompts given.
  • Code generation & auto-completion: In software development, such a model can provide developers with code suggestions and autocompletion to boost their productivity and get coding done faster.
  • Translation: We can use a fine-tuned GPT model for translation tasks, converting text from one language to another with greater precision. For example, the model can be tuned to follow specific grammatical and syntactical rules of different languages, which can lead to higher accuracy translations.
  • Text summarization: We can apply the model in summarizing lengthy texts such as articles, reports, or books. After fine-tuning, it can consistently output summaries that capture the key points and ideas without distorting the original meaning. This could be particularly useful for educational platforms, news services, or any scenario where digesting large amounts of information quickly is crucial.

How much will GPT-3.5 Turbo fine-tuning cost?

There’s the cost of fine-tuning and then the actual usage cost.

  • Training: $0.008 / 1K tokens
  • Usage input: $0.012 / 1K tokens
  • Usage output: $0.016 / 1K tokens

For example, a gpt-3.5-turbo fine-tuning job with a training file of 100,000 tokens that is trained for 3 epochs would have an expected cost of $2.40.

OpenAI, GPT 3.5 Turbo fine-tuning and API updates

When will fine-tuning for GPT-4 be available?

This fall.

OpenAI has announced that support for fine-tuning GPT-4, its most recent version of the large language model, is expected to be available later this year, probably during the fall season. This upgraded model has been proven to perform at par with humans across diverse professional and academic benchmarks. It surpasses GPT-3.5 in terms of reliability, creativity, and its capacity to deal with instructions that are more nuanced.

10 powerful JavaScript animation libraries for engaging user experiences

Animations. A fantastic way to stand out from the crowd and grab the attention of your visitors.

With creative object motion and fluid page transitions, you not only add a unique aesthetic appeal to your website but also enhance user engagement and create a memorable first impression.

And creating animations can’t get any easier with these 10 powerful JavaScript libraries. Scroll animations, handwriting animations, SPA page transitions, typing animations, color animations, SVG animations… they are endlessly capable. They are the best.

1. Anime.js

An animation creating with Anime.js
An animation created with Anime.js.

With over 43k stars on GitHub, Anime.js is easily one of the most popular animation libraries out there.

It’s a lightweight JavaScript animation library with a simple API that can be used to animate CSS properties, SVG, DOM attributes, and JavaScript objects. With Anime.js, you can play, pause, restart or reverse an animation. The library also provides staggering features for animating multiple elements with follow-through and overlapping actions. There are various animation-related events also included, which we can listen to using callbacks and Promises.

Visit the Anime.js website

2. Lottie

An animation created with Lottie.js
An animation created with Lottie.

Lottie is a library that parses Adobe After Effects animations exported as JSON with the Bodymovin plugin and renders them natively on mobile and web applications. This eliminates the need to manually recreate the advanced animations created in After Effects by expert designers. The Web version alone has over 27k stars on GitHub.

Visit the Lottie website

3. Velocity

An animation created with Velocity.
An animation created with Velocity.

With Velocity you create color animations, transforms, loops, easings, SVG animations, and more. It uses the same API as the $.animate() method from the jQuery library, and it can integrate with jQuery if it is available. The library provides fade, scroll, and slide effects. Besides being able to control the duration and delay of an animation, you can reverse it sometime after it has been completed, or stop it altogether when it is in progress. It has over 17k stars on GitHub and is a good alternative to Anime.js.

Visit the Velocity website

4. Rough Notation

Som Rough Notation annotation styles.
Some Rough Notation annotation styles.

Rough Notation is a JavaScript library for creating and animating colorful annotations on a web page. It uses RoughJS to create a hand-drawn look and feel. You can create several annotation styles, including underline, box, circle, highlight, strike-through, etc., and control the duration and color of each annotation style.

Visit the Rough Notation website

5. Popmotion

An animation created with Popmotion.
An animation created with Popmotion.

Popmotion is a functional library for creating prominent and attention-grabbing animations. What makes it stand out? – there are zero assumptions about the object properties you intend to animate, but instead provides simple, composable functions that can be used in any JavaScript environment.

The library supports keyframes, spring and inertia animations on numbers, colors, and complex strings. It is well-tested, actively maintained, and has over 19k stars on GitHub.

Visit the Popmotion website

6. Vivus

An animation created with Vivus.
An animation created with Vivus.

Vivus is a JavaScript library that allows you to animate SVGs, giving them the appearance of being drawn. It is fast and lightweight with exactly zero dependencies, and provides three different ways to animate SVGs: Delayed, Sync, and OneByOne. You can also use a custom script to draw an SVG in your preferred way.

Vivus also allows you to customize the duration, delay, timing function, and other animation settings. Check out Vivus Instant for live, hands-on examples.

Visit the Vivus website

7. GreenSock Animation Platform (GSAP)

An animation created with GSAP

The GreenSock Animation Platform (GSAP) is a library that lets you create wonderful animations that work across all major browsers. You can use it in React, Vue, WebGL, and the HTML canvas to animate colors, strings, motion paths, and more. It also comes with a ScrollTrigger plugin that lets you create impressive scroll-based animations with little code.

Used in over 11 million sites, with over 15k stars on GitHub, it is a versatile and popular indeed. You can use the GSDevTools from GreenSock to easily debug animations created with GSAP.

Visit the GSAP website

8. Three.js

An animation created with Three.js
An animation created with Three.js

Three.js is a lightweight library for displaying complex 3D objects and animations. It makes use of WebGL, SVG, and CSS3D renderers to create engaging three-dimensional experiences that work across a wide range of browsers and devices. It is a well-known library in the JavaScript community, with over 85k stars on GitHub.

Visit Three.js website

9. ScrollReveal

ScrollReveal animations.
ScrollReveal animations.

The ScrollReveal library lets you easily animate a DOM element as it enters or leaves the browser viewport. It provides various types of elegant effects to reveal or hide an element on-scroll in multiple browsers. And quite easy to use too, with with zero dependencies and over 21k stars on GitHub.

Visit the ScrollReveal website

10. Barba.js

Page transitions created with Barba.js.
Page transitions created with Barba.js.

One creative way to make your website outstanding is to add lively transitions between the pages as your users navigate between them. This produces a better user experience than simply displaying the new webpage or reloading the browser.

And that’s why Barba.js is so useful; this library lets you create enjoyable page transitions by making the site run like a Single Page Application (SPA). It reduces the delay between pages and minimizes the number of HTTP requests that the browser makes. It’s gotten almost 11k stars on GitHub.

Visit Barba.js website

Bonus

11. Mo.js

An animation created with Mo.js
An animation created with Mo.js.

Great library for creating compelling motion graphics.

It provides simple, declarative APIs for effortlessly creating smooth animations and effects that look great on devices of various screen sizes. You can move HTML or SVG DOM elements, or you can create a special Mo.js object, which comes with a set of unique capabilities. It is a reliable and well-tested library, with over 1500 tests written and over 17k stars on GitHub.

Visit the Mo.js website

12. Typed.js

An animation created with Typed.js

The name says it all; an animated typing library.

It types out a specific string character by character as if someone was typing in real-time, allowing you pause the typing speed, and even pause the typing for a specific amount of time. With smart backspacing, it types out successive strings starting with the same set of characters as the current one without backspacing the entire preceding string – as we saw in the demo above.

Also included is support for bulk typing, which types out a group of characters on the screen at the same time, instead of one after the other. Typed.js has over 12k stars on GitHub and is trusted by Slack and Envato.

Visit the Typed.js website

Final thoughts

The world of web animation is vast and dynamic, constantly evolving with the advent of new technologies and libraries. The animation libraries highlighted in this article offer an array of features to create engaging, interactive, and visually appealing experiences for users. They are a testament to the power and flexibility of JavaScript, and demonstrate how animations greatly enhance the user experience.

As a developer, harnessing these tools will no doubt elevate your projects, making them stand out in an increasingly competitive digital landscape.

How to move a line or selection up or down in VS Code

To move a line up or down in Visual Studio Code, use this keyboard shortcut:

  • Windows and Linux: Alt + ↑ (Up arrow) to move line up; Alt + ↓ (Down arrow) to move line down.
  • Mac: Option + ↑ to move line up; Option + ↓ to move line down.
Moving a line up or down in Visual Studio Code.

Move selection up or down in VS Code

Similarly, to move a selection up or down in Visual Studio Code, use this keyboard shortcut:

  • Windows and Linux: Alt + ↑ (Up arrow) to move selection up, Alt + ↓ (Down arrow) to move selection down.
  • Mac: Option + ↑ to move selection up, Option + ↓ to move selection down.
Moving a selection up or down in Visual Studio Code.

Why would you need to move a line/selection up or down in code?

  1. Refactoring: When cleaning up your code, you may need to move lines of code around in and out of functions and classes, to make it more readable and maintainable.
  2. Debugging: Like when fixing that error caused by using a variable before declaration/initializing it; with the keyboard shortcuts you easily move the declaration line up before the usage.
  3. Changing control flow: For those instances where the order of function calls or assignments need to change to reflect a new code logic update.

Commands in Visual Studio Code

In VS Code, we have commands, defined actions that carry our various operations in the editor.

We can easily run a command with the Command Palette, which we can access with these keyboard shortcuts:

  • Windows / Linux: Ctrl + Shit + P
  • Mac: Command + Shift + P

The Move Line Up command in VS Code

To move a line/selection up in Visual Studio Code, we use the Move Line Up command.

Moving a line up with the Move Line Up command.

Or with the keyboard shortcuts:

  • Windows/Linux: Alt + ↑ (Up arrow)
  • Mac: Option + ↑
Moving a line up in Visual Studio Code with the keyboard shortcut.

The Move Line Down command in VS Code

In the same manner, to move a line/selection down in Visual Studio Code, we use the Move Line Down command.

Moving a line down in Visual Studio Code with the Move Line Down command

Or with the keyboard shortcuts:

  • Windows/Linux: Alt + ↓ (Down arrow)
  • Mac: Option +
Moving a line down with keyboard shortcuts

Change keyboard shortcut to move line up or down

Personally, I think they’re fine, but if you don’t like the keyboard shortcut to move the line up or down, then navigate to the Keyboard Shortcuts page and change the keybinding for the Move Line Up and Move Line Down commands.

There are multiple ways to get this page; you can click the Keyboard Shortcuts item on the Manage popup shown below or use the shortcut next to the text (Ctrl + K Ctrl + S) here.

Opening the Keyboard Shortcuts page from the Settings popup

To change the keybinding, search for “move line up” or “move line down” in the search bar.

Searching for the Move Line Up command in the Keyboard Shortcuts page
Searching for the Move Line Down command in the Keyboard Shortcuts page of VS Code

Then double-click on the Move Line Up or Move Line Down command, type a new keyboard shortcut, and press the Enter key to carry out the change.

Changing the default keybinding for the Move Line Down command

The change here was Ctrl + E, Ctrl + E – certainly not the smartest choice, but now you’ve seen how it works.

Key takeaways

  • To move a line or selection up or down in Visual Studio Code, use the Alt + ↑ (Up arrow) for up and Alt + ↓ (Down arrow).
  • Moving lines or selections up or down in code can be useful for refactoring, debugging, and changing control flow.
  • You can change the keyboard shortcut to move a line up or down by changing the Move Line Up and Move Line Down command.