模块系统
公开模块
exports.fun1 = function(){
console.log("fun1");
}
exports.fun2 = function(name){
console.log("---"+name);
}
var a = require('./mod.js');
a.fun1();
a.fun2("123");
Node.js 提供了exports 和 require 两个对象,其中 exports 是模块公开的接口,require 用于从外部获取一个模块的接口,即所获取模块的 exports 对象。
mod.js 通过 exports 对象把 fun1/fun2 作为模块的访问接口,在 main.js 中通过 require('./mod.js') 加载这个模块,然后就可以直接访问main.js 中 exports 对象的成员函数了
把一个对象封装到模块
function Hello() {
var name;
this.setName = function(thyName) {
name = thyName;
};
this.sayHello = function() {
console.log('Hello ' + name);
};
};
module.exports = Hello;
var Hello = require('./hello.js');
hello = new Hello();
hello.setName('BYVoid');
hello.sayHello();
fs教程
读取文件
fs.readFile('out.txt', 'utf-8', function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
fs.readFile('sample.png', function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
console.log(data.length + ' bytes');
}
});
var data = fs.readFileSync('output.txt', 'utf-8');
console.log(data);
写入文件
fs.writeFileSync('output.txt', "123");
fs.writeFile("out.txt","ABC123",function(err){
if(err){
console.log("错误:"+err);
}
else{
console.log("oK");
}
});
writeFile()的参数依次为文件名、数据和回调函数。如果传入的数据是String,默认按UTF-8编码写入文本文件,如果传入的参数是Buffer,则写入的是二进制文件。回调函数由于只关心成功与否,因此只需要一个err参数。
获取文件信息
fs.stat('out.txt', function (err, stat) {
if (err) {
console.log(err);
} else {
console.log('isFile: ' + stat.isFile());
console.log('isDirectory: ' + stat.isDirectory());
if (stat.isFile()) {
console.log('size: ' + stat.size);
console.log('birth time: ' + stat.birthtime);
console.log('modified time: ' + stat.mtime);
}
}
});
文件流读取文件
var count = 0;
var str = "";
rs = fs.createReadStream("out.txt");
rs.on('data',(data)=>{
str += data;
count++;
})
rs.on('end',()=>{
console.log(str);
console.log(count);
})
方法的简写
var app={
run1:function(){
console.log("123");
},
run2(){
console.log("111123");
}
}
app.run1();
app.run2();
获取异步方法里面数据
回调函数callback
function getData(callback){
setTimeout(function(){
var name = 'xxxx';
callback(name);
}, 100);
}
getData(function(data){
console.log(data);
});
Promise
var p = new Promise(function(res,rej){
setTimeout(function(){
res("成功1");
}, 100);
rej("失败");
});
p.then(function(data){
console.log(data);
})
p.then((data)=>{
console.log(data);
})