使用 Javascript 创建后端(第二部分):NodeJS 模块系统
这里有一系列文章可以帮助您使用 Javascript 创建后端应用程序。
Node.js 现在是必需的,因此开发人员掌握它是必不可少的。
我将每两天发布一篇新文章,逐渐地您将了解有关 Node.js 的所有知识。
为了不错过任何内容,请在 Twitter 上关注我:https://twitter.com/EricTheCoder_
NodeJS 模块系统
在文件中编写代码是可以的,但如果您的应用程序需要大量代码,您的文件很快就会变得太大。
这就是为什么最好将代码分成几个模块(文件)以使代码可重用且结构更好。
这是一个例子
应用程序.js
const name = 'Mike Taylor'
const greeting = function(name) {
console.log(`Hello ${name}, welcome to NodeJS`)
}
greeting(name)
让 Greeting 模块可复用可能很有趣。为此,我们将它放在一个名为 Greeting.js 的文件中。
const greeting = function(name) {
console.log(`Hello ${name}, welcome to NodeJS`)
}
默认情况下,NodeJS 不允许在其他模块中使用此函数。为此,你必须向模块指示哪些元素可以导出:
const greeting = function(name) {
console.log (`Hello ${name}, welcome to NodeJS`)
}
module.exports = greeting
注意这里最后一行“module.exports = Greeting”,该函数允许使用来自另一个模块的 Greeting 函数。
现在,您可以从 app.js 使用“require”函数加载此模块
const greeting = require('./greeting.js')
const name = 'Mike Taylor'
greeting(name)
“require”函数将使用greeting模块创建一个引用,并将该引用放在constgreeting变量中(该变量可以使用greeting以外的其他名称)
请注意,函数 require ('./greeting.js') 使用路径 './',这允许向 NodeJS 指示该模块与我们的 app.js 文件位于同一文件夹中
多个导出
可以使用 module.exports 函数导出多个元素。以下是示例:person.js
const name = 'Mike Taylor'
const car = 'Ford Mustang'
module.exports = {name, car}
因此,使用包含多个元素的对象完成多次导出。
const person = require('./ person.js')
console.log(person.name, person.car)
请注意,“person”变量并非直接指向“name”或“car”,而是指向导出的对象。因此,要返回其内容,我们必须使用“person.name”。
多重导出(替代语法)
可以使用 module.exports 函数导出多个元素。以下是示例:person.js
const name = 'Mike Taylor'
const car = 'Ford Mustang'
module.exports.name = name
module.exports.car = car
用法保持不变:
const person = require('./ person.js')
console.log(person.name, person.car)
也可以使用解构
const {name, car} = require('./ person.js')
console.log(name, car)
'require' 函数执行模块
当执行 require 函数时,模块会立即执行。这里有一个例子
// hello.js
const hello = function() {
console.log('Hello World')
}
modules.exports = hello
// app.js
const hello = require('./ hello.js')
NodeJS 执行此行代码后,hello模块也会执行。本例中,模块只执行了导出操作,但如果模块中包含代码,则会执行该操作。以下是示例
// hello.js
const hello = function() {
console.log('Hello World')
}
console.log('Hello Node!')
modules.exports = hello
// app.js
const hello = require('./ hello.js')
Hello()
如果您启动了 app.js,您将看到它将在“Hello World”之前显示“Hello Node!”,因为如上所述,“require”执行了该模块。
在创建模块时考虑到这一事实,以避免出现不必要的行为。
结论
今天就到这里,请在推特上关注我:https://twitter.com/EricTheCoder_以便收到下一篇文章发布的通知(两天内)。
文章来源:https://dev.to/ericchapman/create-a-backend-in-javascript-nodejs-module-system-4165