Node.js 18: fetch API, Test Runner module, and more

navarroaxel

Axel Navarro

Posted on April 19, 2022

Node.js 18: fetch API, Test Runner module, and more

This week Node.js v18 was released and we can find new amazing features in this major release. Let's check the most important ones. πŸš€

The fetch API

Say good bye to the node-fetch package, now the fetch API is available on the global scope by default.

const res = await fetch('https://api.belo.app/public/price');
if (res.ok) {
  const data = await res.json();
  console.log(data);
}
Enter fullscreen mode Exit fullscreen mode

We can make requests like we do in browsers. πŸ™Œ

Test Runner module

Now, we can create tests in Node.js without needing an external package.

import test from 'node:test';
import assert from 'node:assert';

test('synchronous passing test', (t) => {
  // This test passes because it does not throw an exception.
  assert.strictEqual(1, 1);
});
Enter fullscreen mode Exit fullscreen mode

Also, we can group subtests within a parent test.

test('top level test', async (t) => {
  await t.test('subtest 1', (t) => {
    assert.strictEqual(1, 1);
  });

  await t.test('subtest 2', (t) => {
    assert.strictEqual(2, 2);
  });
});
Enter fullscreen mode Exit fullscreen mode

Learn more at https://nodejs.org/dist/latest-v18.x/docs/api/test.html.

Prefix-only core module

Have you seen this strange import?

import test from 'node:test';
Enter fullscreen mode Exit fullscreen mode

Since this release all core modules can be imported using the node: prefix, there is no difference between importing fs and node:fs. But the test module only can be imported using the prefixed form: node:test.

πŸ’‘ If when loading node:test the node: prefix is not included, Node.js will attempt to load a module named test from the node_modules folder.

The V8 10.1

Node.js v18 comes with V8 engine v10.1 which is part of Chromium v101, in spite of the versions included in Node.js v17 that didn't include these features:

Conclusion

We've only mentioned the most notable changes in this release. Node.js v18 will be promoted to LTS in October of this year.

You can check the full changelog here.

πŸ’– πŸ’ͺ πŸ™… 🚩
navarroaxel
Axel Navarro

Posted on April 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related