不积跬步,无以至千里;不积小流,无以成江海。

Node.js-函数调用和模块引用(require)

Node.js 康康 1409℃ 3评论

一、函数调用

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)

喜欢 (2)or分享 (0)
发表我的评论
取消评论

 

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(3)个小伙伴在吐槽
  1. 😀
    Chen2017-07-31 14:43 回复
  2. nodejs很牛
    hurry2017-07-31 15:20 回复
    • hehe
      Chen2017-07-31 15:20 回复