Reputation: 772
Recently, while using a linter, I discovered that the names of some built-in packages where prepended with node:
. I searched a lot but I didn't get any useful info. What is this node:module
syntax?
Upvotes: 26
Views: 9578
Reputation: 371
To add to the marzelin's answer, why would you want to specify node:
prefix?
That's because NPM package names and builtin library names can conflict. For example, there's test package on NPM, and node:test
builtin library
There are only few builtin libraries whose names are taken by an NPM package. To avoid ambiguity, you must import them with node:
prefix. So import 'test'
does not work, unless you have NPM package test
installed, but import node:test
works. For full list of such libraries, see the docs
Does it mean that if accidentally install (directly or via dependencies-of-depdencies) NPM package with name http
, you end up importing third-party code? No. Luckily all other builtin libraries are not valid NPM package names.
You can see the rules for package names here
Also, here's the code that is used to tell if given name is a valid NPM package name. That part specifically checks whether the name is in require('module').builtinModules
, and if so, it is not allowed:
const { builtinModules: builtins } = require('module')
// ...code...
// core module names like http, events, util, etc
if (builtins.includes(name.toLowerCase())) {
warnings.push(name + ' is a core module name')
}
Upvotes: 2
Reputation: 11600
Core modules can also be identified using the node: prefix, in which case it bypasses the require cache. For instance, require('node:http') will always return the built in HTTP module, even if there is require.cache entry by that name.
https://nodejs.org/api/modules.html
Upvotes: 28