Introduction to the require. resolve Method in Node. js, noderequire. resolve

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.