一、函数调用
nodejs实质就是js,因此函数调用和js无差别
写一个函数
function hello(msg){
console.log(msg);
}
//调用
hello("hello world!");
//控制台输出
hello world!
二、模块引用
在nodejs中如何调用其他js文件的方法呢,可以使用require引入模块
写一个 modelA.js 使用module.exports声明该模块可被其他模块引入
function ModalA() {
console.log("this is ModelA");
}
module.exports = ModalA; //使用module.exports声明该模块可被其他模块引入
在 server.js中引入模块ModelA
var modelA = require("./ModelA"); //引入模块 这里使用相对路径
modelA(); //调用模块里的方法
如果一个模块里有多个方法可以使用对象的形式定义方法并使用module.exports声明导出
仍然是ModelA文件
module.exports = {
"fnA":fnA,
"fnB":fnB,
"fnC":fnC,
}
function fnA() {
console.log("this is fnA");
}
function fnB() {
console.log("this is fnA");
}
function fnC() {
console.log("this is fnA");
}
在 server.js中引入模块ModelA,并调用相应方法
var modelA = require("./ModelA");
modelA.fnA();
modelA.fnB();
modelA.fnC();
转载请注明:左手代码右手诗 » Node.js-函数调用和模块引用(require)


