学习基础:Node.js Express TypeScript Mongodb;
1.Nodejs
1.回调函数:回调函数就是一个通过[函数指针](https://baike.baidu.com/item/%E5%87%BD%E6%95%B0%E6%8C%87%E9%92%88/2674905)调用的函数
function callBackfnc(fnc){
fnc();
}
function sayHello(){
console.log("Hello")
}
callBackfnc(sayHello);
2.文件读写:
var fs = require("fs");
// readFileSync:同步执行
// var readMe = fs.readFileSync("ReadMe.text","utf-8");
// 异步执行
fs.readFile("ReadMe.text","utf-8",function(err,data){
console.log("data",data)
});
console.log("readme")
// 新建文件夹
fs.mkdir("stuff",function(){
// 读取文件
fs.readFile("ReadMe.text","utf-8",function(err,data){
// 写入内容
fs.writeFile("./stuff/copyStuff.text",data,function(){
console.log("Write Success")
})
})
})
3.流
var fs = require("fs");
// 读取流
var myReadStream = fs.createReadStream(__dirname+"/ReadMe.text","utf-8");
// 写入流
var myWriteStream = fs.createWriteStream(__dirname+"/WriteMe.text","utf-8");
myWriteStream.write("测试数据111","utf-8");
myWriteStream.end();
myWriteStream.on("finish",function(){
console.log("Write Success")
})
// var str = "";
// //接收数据的监听函数
// myReadStream.on("data",function(chunk){
// str+= chunk;
// // console.log("chunk",chunk)
// // 写入
// myWriteStream.write(chunk);
// })
// // 读取结束监听事件
// myReadStream.on("end",function(){
// console.log("str",str)
// })
4.服务器
var http = require("http");
var fs = require("fs");
var myReadStream = fs.createReadStream(__dirname + "/index.html", "utf-8")
function startServer() {
var server = http.createServer(function (req, res) {
var url = req.url;
switch (url) {
case "/plain":
res.writeHead(200, {
"Content-type": "text/plain"
});
res.write("Hey I Got It");
res.end();
break;
case "/json":
res.writeHead(200, {
"Content-type": "application/json"
});
var myJson = {
name: "zpwan",
age: "18",
date: new Date()
};
res.end(JSON.stringify(myJson));
break;
case "/html":
res.writeHead(200, {
"Content-type": "text/html"
});
myReadStream.pipe(res);
break;
default:
break;
}
})
server.listen(2828);
console.log("Server Start on 127.0.0.1:2828")
}
module.exports.startServer = startServer
startserver.js:
var startServer = require("./request");
startServer.startServer();
网友评论