Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the _ _ dirname and _ _ filename variables in nodejs

Shulou Source: shulou.com Published: 2022-06-02 08:39:26 10月03日 Update

This article introduces the knowledge of "how to use the _ _ dirname and _ _ filename variables in nodejs". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Problem background

The background of writing this article is that we encountered a magical error today. Let's take a look at it together.

/ / index.jsconsole.log (_ _ filename); / / execute node index.js// ReferenceError: _ _ filename is not defined in ES module scope

Accessing the global variable _ _ filename in the node environment unexpectedly reported an error, what is the reason? So began to explore all the way, and finally found the root of the problem.

2. Node module mechanism

We know that the early node.js module standard adopted the commonjs module specification, but in the nodejs version v13.2.0, we began to support the ES Modules module specification, and we can use ES Modules modules in node in the following ways

Name the file suffix .mjs

Package.json added "type": "module" field

When we use ES Modules in node, the following global objects and variables will not be available

Require

Module.exports

Exports

_ _ filename

_ _ dirname

NODE_PATH

3. Why can I use _ _ filename and _ _ dirname with commonjs modularization?

This problem is mainly attributed to the running mechanism of nodejs under the commonjs module. Many people may think that _ _ filename is a global variable in the node environment. When this problem occurs, we realize that these two are not really global variables in Node.

Look at a simple piece of js code

(function () {console.log (arguments) / / [1mem2 / 3]}) (1 / 2 / 3)

Arguments can get the parameters passed in when the function is called inside the function.

We execute the following code in the node commonjs module

/ / index.jsconsole.log (arguments) [Arguments] {'0: {},'1: [Function: require] {resolve: [Function: resolve] {paths: [Function: paths]}, main: Module {id:'., path:'E:\\ nodeProjectStorehouse\\ nodeStudyFromBook', exports: {}, filename:'E:\ nodeProjectStorehouse\\ nodeStudyFromBook\\ cc.cjs', loaded: false, children: [] Paths: [Array]}, extensions: [Object: null prototype] {'.js': [Function (anonymous)], '.json': [Function (anonymous)], '.node': [Function (anonymous)]}, cache: [Object: null prototype] {'E:\ nodeProjectStorehouse\ nodeStudyFromBook\\ cc.cjs': [Module]}} Module {id:'., path:'E:\\ nodeProjectStorehouse\\ nodeStudyFromBook', exports: {}, filename:'E:\\ nodeProjectStorehouse\\ nodeStudyFromBook\\ cc.cjs', loaded: false, children: [], paths: ['E:\\ nodeProjectStorehouse\\ nodeStudyFromBook\\ node_modules','E:\ nodeProjectStorehouse\\ node_modules' 'e:\\ node_modules']}, '3percent:' E:\\ nodeProjectStorehouse\\ nodeStudyFromBook\\ cc.cjs', '4percent:' e:\\ nodeProjectStorehouse\\ nodeStudyFromBook'

We can see that arguments has five parameters, which are exports, require, module, _ _ filename, _ _ dirname

At this point, we know clearly that _ _ filename is not a global variable, but a parameter passed in by the outer layer.

In that case, let's visit arguments under the ES Modules module to see what the result is.

/ / index.js ES modulesconsole.log (arguments); / / ReferenceError: arguments is not defined4. How to use _ _ filename and _ _ dirname under ES Modules?

Node official documentation suggests using import.meta.url in disguised form to provide

/ / import.meta.url returns the absolute `module: `URL of the module. / / the fileURLToPath () function in the url module, which returns the fully parsed platform-specific Node.js file path / / the dirname () function in the path module, and the directory path import {fileURLToPath} from 'url';import {dirname} from' path';const _ _ filename = fileURLToPath (import.meta.url); const _ dirname = dirname (_ _ filename) This is the end of the introduction to "how to use the _ _ dirname and _ _ filename variables in nodejs". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Module variable global function parameter problem path code content that is file more mechanism environment knowledge background practical clear magical learned Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker MariaDB MySQL Huawei Apple