Node.js入门(二)

文章目录

          • 事件
          • 读写文件,创删目录
          • 传输Json格式的数据

事件
var event = require('events');

var myEmitter = new event.EventEmitter();

myEmitter.on('someEvent', function(message){//新建一个事件,包括事件名和激发的函数
    console.log(message);
});

myEmitter.on('2', function(message){
    console.log(message);
})

myEmitter.emit('someEvent', 'the event was emitted');
myEmitter.emit('2', 'I am coming!');
读写文件,创删目录
var event = require('events');
var util = require('util');
var fs = require('fs');

// fs.writeFile('readMe.txt', 'Please read me!', 'utf8', function(){
// console.log('write is over!');
// });
fs.mkdir('stuff', function(){
    fs.readFile('readMe.txt', 'utf8', function(err, data){
        fs.writeFile('./stuff/writeMe.txt', data, function(){
            console.log('copy successfully!');
        })
    })
})
fs.rmdir('stuff', function(){
    console.log('remove successfully')
})
传输Json格式的数据
var http = require('http');

var onRequest = function(request, response){
    console.log('Request receive');
    response.writeHead(200, {'Content-Type': 'application/json'});
    var myObj = {
        name: "hfpp23",
        job: "programmer",
        age:27
    };
    response.end(JSON.stringify(myObj));//序列化,转换为字符串,方便传输, parse反序列化,还原为Json格式
}

var server = http.createServer(onRequest);

server.listen(8000);

console.log('Server running at http://127.0.0.1:8000/');

你可能感兴趣的:(开发网站)