Get the App
SLTechnology News&Howtos  ›  Development  › 

How to introduce and use variables and functions between files in node.js

Shulou Source: shulou.com Published: 2022-06-03 15:07:36 10月20日 Update

Editor to share with you how to introduce files in node.js and use variables and functions with each other, I believe most people do not know much about it, so share this article for your reference. I hope you will gain a lot after reading this article. Let's learn about it together.

For general js files, we reference them in html using the

What happens when one js file wants to use variables or functions in another js file when all the js files are used in the node.js project? The use of tag pairs for introduction in js files is not allowed, so the require () function is specified in node.js for introduction.

Require ("test.js")

There are a few points to pay attention to when introducing using require ():

Declare a variable to receive the incoming object when you need to call a variable, function, or object in the incoming file

Var res = require ("foo.js")

When you want other files to be able to call some variables or functions of this file after introducing this file, you need to declare the allowed variables or functions in this file.

/ / foo.jsvar a = 1 foo.a function say () {console.log (a);} exports.a = a politic exports.say = say;//index.jsvar foo = require (foo.js); console.log (foo.a)

When the imported js file is treated as an object, exports should not be used in the form of the moudle.exports = constructor

/ / view.jsfunction View () {} View.prototype.test = function () {console.log ('test')} View.test1 = function () {console.log (' test1')} moudle.exports = view;//test.js var x = require ('. / foo') Console.log (x) / / {[Function: View] test1: [Function]} console.log (x.test) / / undefined console.log (x.test1) / / [Function] x.test1 () / / test1

When using the require () function for file introduction, the default is to add the moudles_lib folder first and then look for the file step by step when it is not available. In addition, you can also use environment variables to set the path of the load module for node.js.

These are all the contents of the article "how to introduce and use variables and functions between files in node.js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Files functions variables objects articles between content not much most forms how to do folders more tags modules environment knowledge industry information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft NVidia Shulou Information vpn Shulou Technology