1.引用模块:使用exports
(1)引用函数或者变量 exports.msg=msg;
引用foo.js中的变量和函数:
var foo=require("./test/foo.js");//在使用中只需要require一次
console.log(foo.msg);
foo.showName();
foo.js:
var msg="hello";
var name="DL";
function showName(){
console.log(name);
};
//使用这种方式来暴露
exports.msg=msg;
exports.name=name;
exports.showName=showName;
(2)引用一个类 module.exports=构造函数
var People=require("./test/people.js");
var DL=new People("DL","woman","23");
DL.showInfo();
people.js:
function People(name,sex,age){
this.name=name;
this.sex=sex;
this.age=age;
};
People.prototype={
showInfo:function(){
console.log(this.name+this.sex+this.age);
}
}
//People被视为构造函数,可以用new来实例化
module.exports=People;
(3)如果在require的没有写./,此时是一个特殊路径,认为文件people.js是node_modules目录下的一个文件。
var People=require("people.js");
(4)使用文件夹来管理模块
var foo=require("foo");//将去寻找node_modules目录下foo文件夹中的index.html页面
(5)require()中的路径是从当前这个文件去寻找,是用相对路径;而fs是从命令提示符的位置开始去寻找,最好是要用绝对路径__dirname。
fs.readFile(__dirname + "/1.txt",function(err,data){
if(err) { throw err; }
console.log(data.toString());
});
2. npm 命令
(1)npm install 模块名字 配置模块
(2)npm init 初始化一个package.json文件
(3)npm install 安装所有互相依赖的包