Home  >  Article  >  Web Front-end  >  Introduction tutorial examples between files in node.js

Introduction tutorial examples between files in node.js

零下一度
零下一度Original
2017-06-30 18:03:081718browse

The basic syntax of node.js is the syntax of JavaScript, so it is easier for students who know JavaScript. As for the configuration of the environment, it is relatively simple. You can visit the official documentation for installation. Here I will share some things I have summarized during my study. This is the first article to talk about how to introduce and use variables and functions between files.

For general js files, we use

<script type="text/javascript" src="test.js"></script>

to reference in html. In the node.js project, all js files are used. When a js file wants to use another js What should I do if there are variables or functions in the file? It is not allowed to use the 9be8c280d3dc51bb61988971f6c2aa5c2cacc6d41bbb37262a98f745aa00fbf0 tag pair in a js file to import it, so node.js stipulates that the require() function should be used to import it

require("test.js");

You need to pay attention to several points when using require() to import:

When you need to call variables and functions in the imported file Or when it is an object, declare a variable to receive the imported object


var res = require("foo.js");

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

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

When the imported js file is treated as an object, you should not use exports and should use moudle.exports = constructor Form


//view.jsfunction View(){ } View.prototype.test = function(){  console.log(&#39;test&#39;) } View.test1 = function(){  console.log(&#39;test1&#39;) }moudle.exports = view;//test.js var x = require(&#39;./foo&#39;); 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 to import files, by default, the moudles_lib folder will be added first, and then the file will be searched for step by step if it does not exist. In addition, you can also use environment variables to set the path to load the node.js module.

The above is the detailed content of Introduction tutorial examples between files in node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn