本系列学习文档是学习其它文章的时候,摘录和总结的内容,版权归原作者所有
参考文献:
《Node.js开发指南》
菜鸟教程
安装相关
安装
brew install node
查看版本
node -v
运行程序
node test.js //传统方式
supervisor test.js //代码更新,自动执行方式,用于服务器类应用
示例代码
服务器
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Node.js</h1>');
res.end('<p>Hello World!</p>');
}).listen(3000);
console.log("HTTP server is listening at port 3000.");
事件
var EventEmitter = require('events').EventEmitter;
var event = new EventEmitter();
event.on('some_event', function() {
console.log('some_event occured.');
});
setTimeout(function() {
event.emit('some_event');
}, 1000);
模块
导出方法
var name;
exports.setName = function(thyName) {
name = thyName;
};
exports.sayHello = function() {
console.log('Hello ' + name);
};
var myModule = require('./module');
myModule.setName('Realank');
myModule.sayHello();
或者
导出整个模块(类)
function Hello() {
var name;
this.setName = function(thyName) {
name = thyName; 4
};
this.sayHello = function() {
console.log('Hello ' + name);
};
};
module.exports = Hello;//导出模块
var Hello = require('./hello');
hello = new Hello();
hello.setName('Realank');
hello.sayHello();
NPM
初始化项目的package.json
npm init