Node.js基础代码⽰例,带注释
'use strict';
var http = require('http');
//端⼝号
var port = v.PORT || 1337;
/**
* 回调函数的使⽤
*/
//回调函数
var fs = require("fs");
//回调函数
if (err) (err);
console.String());
});
/************end**************/
/**
* 事件驱动程序
*/
//引⼊events模块
var events = require('events');
//创建eventEmitter对象
var eventEmitter = new events.EventEmitter();
//创建时间处理程序
var connectHandler = function conneted() {
console.log("connect success.");
//触发 data_received 事件
}
//绑定connection 事件处理程序
<('connection', connectHandler);
//使⽤匿名函数绑定data_received事件
<('data_received', function () {
console.log('received data1 success.');
});
<('data_received', function () {
console.log('received data2 success.');
});
//触发connection事件
setTimeout(function () {
}, 1000);
console.log('program run over.');
/************end**************/
/
************Buffer对象************/
var buf = Buffer.alloc(26);
for (var i = 0; i < 26; i++) {
buf[i] = i + 97;
}
console.String('ascii'));// 输出: abcdefghijklmnopqrstuvwxyz
console.String('ascii', 0, 5)); // 输出: abcde
console.String('ascii', 0, 5)); // 输出: abcde
console.String('utf8', 0, 5));    // 输出: abcde
console.String(undefined, 0, 5)); // 使⽤ 'utf8' 编码, 并输出: abcde
//buffer转Json
var buffer2json = Buffer.from('aabbc!');
var _json = JSON(buffer2json);
console.log("The Buffer2Json is " + _json);
//缓冲区合并
var buffer1 = Buffer.from('Me');
var buffer2 = Buffer.from(' QinShiHuang');
var buffer3 = Buffer.from(' DaQian');
var buffer4 = at([buffer1, buffer2, buffer3]);
console.log("The concat result is " + String());
//缓冲区⽐较
//返回⼀个数字,表⽰ buf 在 otherBuffer 之前,之后或相同。
var cBuffer1 = Buffer.from('ABC');
var cBuffer2 = Buffer.from('ABCD');
console.log("The compare result is ")
var compareResult = cBuffer1pare(cBuffer2);
if (compareResult < 0) {
console.log(cBuffer1 + ' at before of ' + cBuffer2);
url编码和utf8区别} else if (compareResult == 0) {
console.log(cBuffer1 + ' at after of ' + cBuffer2);
} else {
console.log(cBuffer1 + ' is equal of ' + cBuffer2);
}
/
/拷贝缓冲区
var copyBuffer1 = Buffer.from('I Hate You!');
var copyBuffer2 = Buffer.from('Love');
//将 buf2 插⼊到 buf1 指定位置上
console.log("The copy content is " + String());
//缓冲区裁剪
var sliceBuffer1 = Buffer.from('you are');
var sliceBuffer2 = sliceBuffer1.slice(0, 3);
console.log("sliceBuffer2 content : " + String());
/************end**************/
/
*******************Stream流start**********************/
var streamData = '';
//创建可读流
var readerStream = fs.createReadStream('./');
//设置编码为utf-8
readerStream.setEncoding('UTF8');
//处理流事件-->data,end,and error
<('data', function (chunk) {
streamData += chunk;
});
<('end', function () {
console.log(streamData);
});
<('error', function (err) {
console.log(err.stack);
});
console.log('stream run over!');
//写⼊流
var writeData = 'this is a very good thing,dont worry';
// 创建⼀个可以写⼊的流,写⼊到⽂件 中
// 创建⼀个可以写⼊的流,写⼊到⽂件 中
var writeStream = fs.createWriteStream('./');
/
/ 使⽤ utf8 编码写⼊数据
writeStream.write(writeData, 'UTF8');
// 标记⽂件末尾
// 处理流事件 --> finish, and error
<('finish', function () {
console.log('Write success.');
});
<('error', function (err) {
console.log(err.stack);
});
/
/管道流
//读取⼀个⽂件并写⼊另⼀个⽂件
//创建⼀个可读流
var rStream = fs.createReadStream('./');
//创建⼀个可写流
var wStream = fs.createWriteStream('./');
//管道读写操作
//读取的⽂件内容,并将内容写⼊⽂件中
rStream.pipe(wStream);
console.log("Read and Write Over!");
//链式流
/
/压缩⽂件
var zlib = require('zlib');
//压缩⽂件为
.ateGzip())
.ateWriteStream('./'));
console.log('zip complete!');
//解压⽂件
//fs.createReadStream('./')
//    .ateGunzip())
//    .ateWriteStream('./'));
/
/console.log('zipGun complete!');
/*******************Stream流end**********************/
/*******************模块系统创建对象start**********************/
var Hello = require('./hello');
var hello = new Hello();
hello.setName('Wang Da Niang');
hello.sayHello();
/*******************模块系统创建对象end**********************/
/*******************Node.js函数start**********************/
//⼀个函数可以作为另⼀个函数的参数
function say(word) {
console.log(word);
}
function execute(someFunction, value) {
someFunction(value);
}
execute(say, 'WoZhenDeAiNi!');
//匿名函数,⽅法隐藏在参数中
execute(function (word) { console.log('NiMing:' + word); }, 'BuXiangShuoHua') /*******************Node.js函数end**********************/
/*******************Node.js全局对象start **********************/
//输出全局变量_filename的值,__filename 表⽰当前正在执⾏的脚本的⽂件名。它将输出⽂件所在位置的绝对路径,且和命令⾏参数所指定的⽂件名不⼀定相同console.log(__filename);
// 输出全局变量 __dirname 的值,__dirname 表⽰当前执⾏脚本所在的⽬录。
console.log(__dirname);
//Process属性
//输出到终端
process.stdout.write("Hello World!\n")
//通过参数读取
process.argv.forEach(function (val, index, array) {
console.log(index + ':' + val);
});
//获取执⾏路径
console.Path);
/
/平台信息
console.log(process.platform);
//Process⽅法
//输出当前⽬录
console.log('current direction is :' + process.cwd());
//输出当前版本
console.log('current version is :' + process.version);
//输出内存使⽤情况
console.log('current neicun is :'+Usage());
/*******************Node.js全局对象end**********************/
/************util.inherits继承⽅法start**************/
var util = require('util');
function Base() {
this.name = 'GuoJia';
this.base = 1995;
this.sayHello = function () {
console.log('Hello' + this.name);
};
}
Base.prototype.showName = function () {
console.log(this.name);
}
function Sub() {
this.name = 'Ai';
}
//使Sub继承于Base
util.inherits(Sub, Base);
var objBase = new Base();
objBase.showName();
objBase.sayHello();
console.log(objBase);
var objSub = new Sub();
objBase.showName();
/
/objSub.sayHello();
console.log(objSub);
/************util.inherits继承⽅法end**************/
/************util.inspect⽅法start**************/
//将任意对象转换为字符串的⽅法,通常⽤于调试和错误输出
function Person() {
this.name = 'LiXiuQi';
return this.name;
};
}
var obj = new Person();
console.log(util.inspect(obj));
console.log(util.inspect(obj, true));
/************util.inspect⽅法end**************/
/*******************启动服务start**********************/
var url = require("url");
var route = require('./route.js');
function start(route) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
/
/处理url地址参数
route(pathname);
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
response.writeHead(200, { 'Content-Type': 'text/plain' });
// 发送响应数据 "Hello World"
}
//创建服务
}
ute);
/*******************启动服务end**********************/
// 终端打印信息
console.info("hi this is the first application!");

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。