in

What’s New in Node.js 20—SitePoint

1682298470node js version 20 features

[ad_1]

Node.js version 20 was released on April 18, 2023. It addresses some of the issues and criticisms already “solved” by Deno and Bun, such as the new permissions model and a stable native test runner. In this article, we explore new options available to developers using the world’s most popular JavaScript runtime.

content:

  1. Node.js release schedule
  2. New permission model
  3. native test runner
  4. Compiling a Single Executable Application
  5. Updated V8 JavaScript engine
  6. Other updates

Node.js release schedule

Node.js has a six-month release schedule.

  • April even-numbered releases (14, 16, 18, etc.) are stable and receive 3 years of long-term support (LTS) updates.

  • Odd-numbered October releases (15, 17, 19, etc.) are more experimental and often end up being updated after a year.

In general, you should choose an even-numbered LTS version unless you need a specific feature in an experimental release and don’t plan to upgrade later. However, Node.js 20 is new and the website recommends using version 18 while the development team fixes the latest issues.

Node.js 20 has the following new features…

New permission model

running node somescript.js It’s not without risks. Scripts can do anything from deleting important files, sending private data to a server, running cryptocurrency miners in child processes, and more. It’s hard to guarantee that your own code doesn’t break anything: Are you sure all your modules and their dependencies are safe?

The new (experimental) Node.js Permission Model restricts what scripts can do. To use it, --experimental-permission flag you node After the command line:

  1. --allow-fs-read Allow read access to the file. You can restrict read access to:

    • Specific directory: --allow-fs-read=/tmp/
    • Specific file: --allow-fs-read=/home/me/data.json
    • Or a wildcard file pattern: --allow-fs-read=/home/me/*.json
  2. --allow-fs-write Allows write access to identical directories, files, or files with wildcard patterns.

  3. --allow-child-process Allow child processes, possibly running other scripts written in other languages, etc.

  4. --allow-worker Allow worker threads to run Node.js code in parallel with the main processing thread.

In the following example, somescript.js I can read the file with /home/me/data/ directory:

node --experimental-permission --allow-fs-read=/home/me/data/ somescript.js

When I try to write a file, run another process, or start a web worker, ERR_ACCESS_DENIED error.

You can check permissions within your application using the new process.permission object. For example, here’s how to check if a script can write a file:

process.permission.has('fs.write');

Here’s how to check if a script can write to a particular file:

if ( !process.permission.has('fs.write', '/home/me/mydata.json') ) {
  console.error('Cannot write to file');
}

JavaScript permission management was first introduced by Deno with fine-grained control over access to files, environment variables, operating system information, timing, networking, dynamically loaded libraries, and child processes. Node.js is insecure by default unless you add --experimental-permission National flag. This is ineffective, but allows existing scripts to continue running unchanged.

native test runner

Historically, Node.js has been a minimal runtime, allowing developers to pick and choose the tools and modules they want. Third-party modules such as Mocha, AVA, and Jest were required to run code tests. This has created many options, but it can be difficult to do. number one Switching tools may not be easy.

Other runtimes took a different view, offering built-in tools that were considered essential for development. Deno, Bun, Go, and Rust all provide built-in test runners. Developers have default choices, but they can choose different choices if their project has specific requirements.

Node.js 18 introduced an experimental test runner that is stable at version 20. You can write test scripts without having to install third-party modules.

  • of your project /test/ directory
  • by naming the file test.js, test.mjsagain test.cjs
  • Use test- at the beginning of the file name — etc. test-mycode.js
  • Use test A period (.),hyphen(-) or underscore (_) – like that mycode-test.js, mycode_test.cjsagain mycode.test.mjs

then you can import node:test and node:assert And write a test function:


import { test, mock } from 'node:test';
import assert from 'node:assert';
import fs from 'node:fs';

test('my first test', (t) => {
  assert.strictEqual(1, 1);
});

test('my second test', (t) => {
  assert.strictEqual(1, 2);
});


mock.method(fs, 'readFile', async () => 'Node.js test');
test('my third test', async (t) => {
  assert.strictEqual( await fs.readFile('anyfile'), 'Node.js test' );
});

run the test with node --test test.mjs Examine the output.

✔ my first test (0.9792ms)
✖ my second test (1.2304ms)
  AssertionError: Expected values to be strictly equal:

  1 !== 2

      at TestContext.<anonymous> (test.mjs:10:10)
      at Test.runInAsyncScope (node:async_hooks:203:9)
      at Test.run (node:internal/test_runner/test:547:25)
      at Test.processPendingSubtests (node:internal/test_runner/test:300:27)
      at Test.postRun (node:internal/test_runner/test:637:19)
      at Test.run (node:internal/test_runner/test:575:10)
      at async startSubtest (node:internal/test_runner/harness:190:3) {
    generatedMessage: false,
    code: 'ERR_ASSERTION',
    actual: 1,
    expected: 2,
    operator: 'strictEqual'
  }

✔ my third test (0.1882ms)
ℹ tests 3
ℹ pass 2
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 72.6767

can add --watch Flag to automatically rerun tests when files change:

node --test --watch test.mjs

You can also run all tests found in the project.

node --test

Native testing is a welcome addition to the Node.js runtime. No more excuses for having to learn various third-party APIs. forget To add tests to a small project!

Compiling a Single Executable Application

A runtime is required to run a Node.js project. This can be a barrier to distributing your application to platforms or users who cannot easily install or maintain Node.js.

Version 20 provides an experimental feature that allows you to create Single Executable Applications (SEAs) that can be deployed without dependencies. It’s a little complicated, but the manual explains the process.

  1. Requires a project containing a single-entry script. You should use CommonJS, not ES modules.

  2. Create a JSON configuration file that will be used to build the script into a blob that runs inside the runtime. for example, sea-config.json:

    {
      "main": "myscript.js",
      "output": "sea-prep.blob"
    }
    
  3. generate the blob with node --experimental-sea-config sea-config.json.

  4. Depending on your OS, you should copy node Remove the executable, remove the binary signature, insert the blob into the binary, re-sign it, and test the resulting application.

While it works, it’s limited to older CommonJS projects and can only target the same OS you’re using. Given that the excellent Deno compiler can create an executable for any platform from a JavaScript or TypeScript source file with one command, it is sure to improve.

You should also be aware of the size of the resulting executable.Single person console.log('Hello World'); Node.js (and Deno) needs to add the entire V8 JavaScript engine and standard library, which produces an 85MB file. Options to reduce the file size are being considered, but unlikely to go below 25 MB.

Compilation is impractical for small command line tools, but is a viable option for large projects such as complete web server applications.

Updated V8 JavaScript engine

Node.js 20 includes the latest version of the V8 engine with the following JavaScript features:

Other updates

The following updates and improvements are also available:

summary

Node.js 20 is a big step forward. This is a more significant release and implements some of Deno’s great features.

However, this raises the question: Should I use Deno instead?

Deno is fine. It’s stable, supports TypeScript natively, reduces development time, requires fewer tools, and receives regular updates. The cons are short development times, fewer modules, and often shallow imitations of Node.js libraries.

Deno and Bun are worth considering as new projects, but there are thousands of existing Node.js applications. Deno and Bun make it easier to migrate code, but there are not always clear advantages to migrating away from Node.js.

The good news is that the JavaScript ecosystem is thriving. Runtime teams are learning from each other, and rapid evolution benefits developers.



[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    24ny climate 01 fzvb facebookJumbo

    Governors Island to Be Site of $700 Million Climate Campus

    Andy panel for web

    Content, bundling, UX simplicity and personalization help ensure relevance with pay TV