Introduction to the require. resolve Method in Node. js, noderequire. resolve
Preface
There are many discussions about NodeJs on the Internet. I personally think that NodeJs's programming philosophy and client-side Javascript have maintained a philosophy, and there is no change, but it only adds the "require ()" function, so as long as you learn the require function well, the remaining question is how to better use the API. This article mainly introduces the require. resolve Method in Node. js. Let's take a look at the detailed introduction below.
To put it simply, when using fs in Node. js to read files, you often encounter the absolute path of the file to be spelled out (the relative path of fs processing is subject to the Process Execution directory ).
Previously, the path module and the _ dirname variable were used.
The Code is as follows:
fs.readFileSync(path.join(__dirname, './assets/some-file.txt'));
Use require. resolve to simplify this process
Sample Code:
fs.readFileSync(require.resolve('./assets/some-file.txt'));
In addition, require. resolve will check whether the path exists after splicing the path. If the target path of resolve does not exist, it will throwCannot find module './some-file.txt' Exception. omitted a procedure to check whether the file exists (fs. exists ).
This error does not increase the check burden. After all, if you find that the file does not exist, an exception will be thrown when you use fs to operate the file. otherwise, use require. resovle can be defined as a constant in the file in advance, so an exception can be thrown when the application is started, rather than an exception thrown when the specific operation file is started.
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message. Thank you for your support.