四、node(二)

2017-04-25  本文已影响13人  sheepmiee

node模块

文件模块
内置模块
第三方模块

内置模块

util

util.inherits(Child,Parent)
继承,原理es6的继承方法:Object.setPrototypeOf(Child.prototype,Parent.prototype);只继承公有方法

var util = require('util');
util.inherits();
Buffer

Buffer详解
Buffer是global上的属性,为全局对象

常用全局属性: setTimeout setInterval process setImmediate console Buffer 形参(exports,require,module,__dirname , __filename)
Buffer展现给我们的是16进制,utf8一个汉字 代表3个字节,一个字节由八个位组成Bit

var buffer = new Buffer('开心');
console.log(buffer);//

var buffer = new Buffer([100,120,16]);
console.log(buffer);//<Buffer 64 78 f0>

var buffer = new Buffer([0xfe,0xff,0x16]);
console.log(buffer);//<Buffer fe ff 16>

var obj = {name:1};
var arr = [obj,1,2];
var newArr = arr.slice(0); 
obj.name = 2;
console.log(newArr);//[{name:2},1,2]

buffer:存储的都是内存地址

var buffer = new Buffer([1,2,3]);
var newBuffer = buffer.slice(0,1);
newBuffer[0]=2;
console.log(buffer)//<Buffer 02 02 03>

buffer.forEach(function (item){
console.log(item)//得到的是十进制
});

//1.判断长度是否传递,如果给了长度就构建一个buffer,将小buffer依次拷贝到大buffer上,过长则将多余的部分 截取掉slice()截取有效长度
//2.手动维护长度 在构建buffer,将小buffer依次拷贝到大buffer上 copy

Buffer.myConcat = function (list,totalLength) {
    //1.判断长度是否传递
    if(typeof totalLength == "undefined"){
        totalLength = 0;
        list.forEach(function (item) {
            totalLength += item.length;
        });
    }
    var buffer = new Buffer(totalLength);//1000
    var index = 0;
    list.forEach(function (item) {
        item.copy(buffer,index);
        index+= item.length;
    });
    return buffer.slice(0,index);
};
console.log(Buffer.concat([buf1,buf2,buf1,buf2]).toString());
进制转换
parseInt('11100011',2);//
(0x16).toString(10);//16转10,结果26
//将汉字转换成2进制
var buffer = new Buffer('珠');
console.log(buffer); //0xe7 0x8f 0xa0
console.log((0xe7).toString(2)); //11100111
console.log((0x8f).toString(2)); //10001111
console.log((0xa0).toString(2)); //10100000

//将2进制转换成10进制
console.log(parseInt('00111001',2)); //57
console.log(parseInt('00111000',2)); //56
console.log(parseInt('00111110',2)); //62
console.log(parseInt('00100000',2)); //32

//查找
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
str+= 'abcdefghijklmnopqrstuvwxyz';
str+='0123456789';
str+='+/';
console.log(str[57]+str[56]+str[62]+str[32]);//54+g

fs模块 file system

十组常用的fs模块方法
readFileSync readFile
writeFile writeFileSync
appendFile appendFileSync
path.resolve() path.join() 给一个相对路径 解析一个绝对路径
mkdirSync mkdir 创建目录
rmdirSync rmdir 删除目录
unlinkSync unlink 删除文件
readdirSync readdir 读取目录
existsSync exists 是否存在
statSync stat 判断文件状态

const fs = require('fs');
能用异步绝不用同步
fs.readFileSync

读取文件不存在会报错
读取默认格式是buffer类型 相当于encoding:null

var school = {}; 
fs.readFile('./name.txt','utf8',function (e,data) { //error-first
    if(e)console.log(e);
    school.name = data;
    out();
});
fs.readFile('./age.txt','utf8',function (e,data) { //error-first
    if(e)console.log(e);
    school.age = data;
    out();
});
function out() {
    if(Object.keys(school).length == 2){
        console.log(school); //{name:'珠峰培训',age:8}
    }
}
fs.writeFileSync('./a.txt',new Buffer('珠峰'));//写入的是'珠峰',因为默认是utf8格式,会默认toString('utf8')
fs.writeFile('./a.txt',new Buffer('珠峰'),function(err){});

不覆盖写入2中方法:

 fs.appendfile(target,data,,function (err) {})
 fs.writeFile(target,data,{encoding:'utf8',flag:'a'},function (err) {});
var path  = require('path');
console.log(path.resolve('1.js'));//以当前路径解析出一个相对路径
console.log(path.join(__dirname,'1.js'));//相当于resolve
function copy(source,target) {//异步
    //先读在写
    fs.readFile(source,function (err,data) {
        if(err)console.log(err);
        //appendFile可以进行累加,不清空内容写入
        fs.writeFile(target,data,{encoding:'utf8',flag:'a'},function (err) {
            if(err)console.log(err);
            console.log('拷贝成功');
        });
    });
}
copy('./name.txt','./name1.txt');

function copySync(source,target) { //同步
    var result = fs.readFileSync(source);
    fs.writeFileSync(target,result);
}
copySync('./name.txt','./name1.txt');
function makepSync(p) {
    var arr = p.split('/'); 
    for(var i = 0;i<arr.length;i++){
        var path = arr.slice(0,i+1).join('/');
        if(!fs.existsSync(path)){//exists两个值true false
            fs.mkdirSync(path)
        }
    }
}
makep('a/b/c/d/e/f')

函数模拟:异步创建文件夹

//写一个异步创建  mkdir + exists
//递归   mkdir + exists  插入排序
function makep(p) {
    var paths = p.split('/');
    var index = 1;
    function makeOne(subpath) {
        if(paths.length == index-1){
            return;
        }
        fs.exists(subpath,function (flag) {
            var temp = paths.slice(0,++index).join('/');
            if(!flag){ //不存在的时候创建
                fs.mkdir(subpath,function () {
                    makeOne(temp);// a/b
                });
            }else{ //存在的时候继续下一次
                makeOne(temp);
            }
        });
    }
    makeOne(paths[index-1]);
}
makep('a/b/c/d/e/f');
上一篇下一篇

猜你喜欢

热点阅读