Node.js的基本模块学习(一)

来源:互联网 发布:win10启用不了网络发现 编辑:程序博客网 时间:2024/06/07 08:57

首先写一个hello.js文件:

use' strict; var s='hello'; function greet(name){ console.log(s+','+name+'!'); }module.exports=greet;

  首先看到,函数greet()是hello.js中的,最后面一条语句,将函数greet作为模块输出,个人理解就是类似java中的public属性,那么其他的js文件就可以调用这个函数.
  再写一个main.js文件:
  

'use strict';//引入hello模块:var hi=require('./hello');var s='World!';hi(s);//输出hello,World!

此时可以注意点,hi就相当于hello.js文件中的greet()函数了,通过require()函数将hello模块中暴露的greet()函数传给了变量hi../hello是因为两个文件在同一个目录上,未来避免出错,最后写绝对路径.