安装官网:
https://nodejs.org/en/
运行代码:
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>PCAT</p>‘);
}).listen(3000);
console.log(‘HTTP server is listening at port 3000.‘);
建立app.js 用cmd启动,出现成功
HTTP server is listening at port 3000.
安装调试工具:
npm install -g supervisor
用supervisor启动服务,每次修改代码就不用node启动了。
supervisor app.js 文件名称
同步读取文件:
var fs=require(‘fs‘); var data=fs.readFileSync(‘file.txt‘,‘UTF-8‘); console.log(data); console.log(‘end‘);
  
异步读取文件:
var fs=require(‘fs‘);
fs.readFile(‘file.txt‘,‘UTF-8‘,function(err,data){
    if(err){
        console.log(‘read file err‘);
    }else{
        console.log(data);
    }
});
console.log(‘end‘);
  
写一个简单的自定义事件:
var EventEmitter=require(‘events‘).EventEmitter;
var event=new EventEmitter();
event.on(‘some_event‘,function(){
    console.log(‘这是一个自定义事件‘);
});
setTimeout(function(){
    event.emit(‘some_event‘);
},1000);
  
自定义模块(调用):
var myModule=require(‘./module‘); myModule.setName(‘marico‘); myModule.sayHello();
模块:
var name;
exports.setName=function(thyName){
	name=thyName;
}
exports.sayHello=function(){
	console.log(‘hello‘+name);
}
  
把上面的方法分装一下:
function hello(){
    var name;
    this.setName=function(thyName){
        name=thyName;
    }
    this.sayHello=function(){
        console.log(‘hello ‘+name);
    }
}
//exports.hello=hello;
module.exports=hello;
var hello=require(‘./module.js‘); var he=new hello(); he.setName(‘marico‘); he.sayHello(); var he2=new hello(); he2.setName(‘yfc‘); he2.sayHello();
原文:https://www.cnblogs.com/sunliyuan/p/9901556.html