NodeJS学习笔记(五)

路由

先来看一个url,node将会如何解析其中的数据

//http://locahost:8888/start?fpp=bar&hello=world

url.parse(string).pathname //start
url.parse(string).query //foo=bar&hello=world

querystring.parse(queryString)['foo'] //bar

querystring.parse(queryString)['hello'] //world

一般来讲我们通过request.url获取url

__filename

输出文件所在位置的路径。即使在模块中,被其他地方引用了,返回的依然是模块文件的路径

__dirname

输出文件所在的目录

main.js

console.log(__filename); ///web/com/runoob/nodejs/main.js
console.log(__dirname);///web/com/runoob/nodejs

util

一个nodejs核心模块,提供常用函数的集合弥补核心JavaScript功能过于精简和不足

util.inherits

出现的理由:js面向对象是基于原型的,js没有提供继承的语言级别特性,而是通过原型复制来实现的。

var util = require('util');
function Base(){
    this.name = 'base',
    this.base = 1991;
    this.sayHello = function(){
        console.log('Hello' + this.name);
    };
};


Base.prototype.showName = function(){
    console.log(this.name);
};


function Sub(){
    this.name = 'sub'
};

util.inherits(Sub,Base);  //util.inherits(son,father),其实现在的情况只是继承了Base的prototype属性,其他什么都没有,这很关键

var objBase = new Base();
objBase.showName(); //base
objBase.sayHello();//Hello base
console.log(objBase); //{ name: 'base', base: 1991, sayHello: [Function] }原型的showName并不会出现在打印中

var objSub = new Sub();
objSub.showName(); //sub
objSub.sayHello(); //报错,只继承prototype
console.log(objSub);//{ name: 'sub' }

util.inspect(obj,showHidden,depth,color)

用于将任意对象转化为字符串

showHidden:true,显示更多隐藏信息

depth:对象递归的层数,如果为null,则全部递归完成

color为true:终端更加漂亮效果

var util = require('util'); 
function Person() { 
    this.name = 'byvoid'; 
    this.toString = function() { 
    return this.name; 
    }; 
} 
var obj = new Person();  //记得new一下创建的函数对象
console.log(util.inspect(obj)); 
//Person { name: 'byvoid', toString: [Function] }


console.log(util.inspect(obj, true)); 
//Person {
  name: 'byvoid',
  toString: 
   { [Function]
     [length]: 0,
     [name]: '',
     [arguments]: null,
     [caller]: null,
     [prototype]: { [constructor]: [Circular] } } }

util判断

util.isRegExp(obj)

扫描二维码关注公众号,回复: 2994649 查看本文章

util.isArrary(obj)

util.isData(obj)

是就返回true,不是就false

猜你喜欢

转载自blog.csdn.net/JimmyLLLin/article/details/82257924