node.js基础

1. 全局变量 window

  • console
  • setTimeout(() => {}, 2000)
  • setInterval(() => {}, 2000)
  • __dirname :打印当前文件的路径
  • __filename :输出当前运行文件的路径
  • require
  • exports

2. 回调函数

//简单例子1
function callFunction(fun, name) {
	fun(name);
}
var sayBye = function(name) {
	console.log(name + ' Bye');
}
callFunction(sayBye, 'hpioi'); //hpioi Bye

//简单例子2 常用
function callFunction(fun, name) {
	fun(name);
}
callFunction(function(name) {
	console.log(name + ' Bye');
}, 'hpioi'); //hpioi Bye

3. 模块

//count.js
 var counter = function (arr) {
	return "There are " + arr.length + " elements in the array"; 	
 }
 var adder = function (a, b) {
	return `the sum of the 2 number is ${a + b}`;
 }
 var pi = 3.14;
 //module.exports.counter = counter;
 //module.exports.adder  = adder ;
 //module.exports.pi  = pi ;
 //简写
 module.exports = {
 	counter:counter,
 	adder:adder,
 	pi:pi
 }

//app.js
var stuff = require('./count');
console.log(stuff.counter(['hello','node.js']));//There are 2 elements in the array
console.log(stuff.adder(6, 3));//the sum of the 2 number is 9
console.log(stuff.pi);//3.14

4. 事件

 var events = require('events');
 var myEmitter = new events.EventEmitter();
 myEmitter.on('someEvent', function(msg){
 	console.log(msg);
 })
 myEmitter.emit('someEvent', 'the someEvent was emitted');//the someEvent was emitted
 var events = require('events');//基础事件库
 var util = require('util');//基础工具库
 var Person = function(name) {
 	this.name = name;
 }
 util.inherits(Person, events.EventEmitter);//inherits:继承, Person类继承EventEmitter
 var xiaoming = new Person('xiaoming');
 var lili = new Person('lili');
 var lucy = new Person('lucy');
 var persons = [xiaoming, lili, lucy];
 persons.forEach(function(person) {
 	//绑定事件
	person.on('speak', function(message) {
		console.log(person.name + " said: " + message);
	})
 })
 xiaoming.emit('speak', 'hi');
 lili.emit('speak', 'hello');
 lucy.emit('speak', 'yes');

5. 读写文件(同步,异步)

同步

//readMe.txt
hello hpiooi

//app.js
var fs = require('fs');
var readMe = fs.readFileSync("readMe.txt", "utf8");
console.log(readMe);
console.log('finished');
//结果:
//hello hpiooi
//finished


fs.writeFileSync("writeMe.txt", readMe);//创建writeMe.txt,并把hello hpiooi写进去

异步

//readMe.txt
hello hpiooi

//app.js
var fs = require('fs');
var readMe = fs.readFile("readMe.txt", "utf8", function(err, data) {
	console.log(data);
	fs.writeFile("writeMe.txt", data, function(){
		console.log('writeMe has finished');
	});//把hello hpiooi写进去
};
console.log('finished');
//结果:
//finished
//hello hpiooi
//writeMe has finished

6. 创建和删除目录

删除文件

var fs = require('fs');
fs.unlink("writeMe.txt", function(){
	console.log("delete writeMe.txt");
})

新建目录和删除

var fs = require('fs');
fs.mkdirSync('stuff');//创建目录,同步
fs.mkdir('stuff', function(){
	console.log('创建成功')
});//创建目录,异步
fs.rmdirSync('stuff');// 删除目录

7. 流和管道

var fs = require('fs');
var myReadStream = fs.createReadStream(__dirname + '/readMe.txt', 'utf8');
var myWriteStream = fs.createWriteStream(__dirname + '/writeMe.txt');
//myReadStream.setEncoding('utf8');
var data = ""
myReadStream.on('data', function(chunk) {
	data += chunk;
	myWriteStream.write(chunk);
}) 
myReadStream.on('end', function(){
	console.log(data);
})

管道

var fs = require('fs');
var myReadStream = fs.createReadStream(__dirname + '/readMe.txt', 'utf8');
var myWriteStream = fs.createWriteStream(__dirname + '/writeMe.txt');
myReadStream.pipe(myWriteStream);//管道写入

8. web服务器

 var http = require('http');
 var server = http.createServer(function(request, response){
 	console.log('Request received');
 	response.writeHead(200, {'Content-Type': 'text/plain'});
 	response.write('Hello from out application');
 	response.end();
 })
server.listen(3000);
console.log('Server started on http://localhost:3000');

9.响应JSON

 var http = require('http');
 var server = http.createServer(function(request, response){
 	console.log('Request received');
 	response.writeHead(200, {'Content-Type': 'application/json'});
 	//response.write('Hello from out application');
 	var Obj = {
 		name: "hpiooi",
 		jon: "programmer",
 		age: 25
 	}
 	response.end(JSON.stringify(Obj));
 })
server.listen(3000);
console.log('Server started on http://localhost:3000');

10. 响应HTML页面

//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h2 style="color:brown;">hpiooi</h2>
</body>
</html>
//app.js
var http = require('http');
var fs = require('fs');
var server = http.createServer(function(request, response){
	console.log('Request received');
	response.writeHead(200, {'Content-Type': 'text/html'});
	var htmlFileStream = fs.createReadStream(__dirname + '/index.html');
	htmlFileStream.pipe(response);
})
server.listen(3000);
console.log('Server started on http://localhost:3000');

11. 用模块化思想组织代码

//server.js
var http = require('http');
var fs = require('fs');

function startServer() {
    var server = http.createServer(function(request, response){
        console.log('Request received');
        response.writeHead(200, {'Content-Type': 'text/html'});
        var htmlFileStream = fs.createReadStream(__dirname + '/index.html');
        htmlFileStream.pipe(response);
    })
    server.listen(3000);
    console.log('Server started on http://localhost:3000');
}

exports.startServer = startServer
//app.js
var server = require('./server');

server.startServer();

12. 路由

//server.js
var http = require('http');
var fs = require('fs');

function startServer() {
    var server = http.createServer(function(request, response){
        console.log('Request received' + request.url);
        if(request.url === '/' || request.url === '/home') {
            response.writeHead(200, {'Content-Type': 'text/html'});
            fs.createReadStream(__dirname + '/index.html').pipe(response);
        }else if(request.url === '/text') {
            response.writeHead(200, {'Content-Type': 'text/plain'});
            fs.createReadStream(__dirname + '/index.html').pipe(response);
        }else if(request.url === '/api/person'){
            response.writeHead(200, {'Content-Type': 'application/json'});
            var Obj = {
                name: "hpiooi",
                jon: "programmer",
                age: 25
            }
            response.end(JSON.stringify(Obj));
        }else {
            response.writeHead(200, {'Content-Type': 'text/html'});
            fs.createReadStream(__dirname + '/404.html').pipe(response);
        }
    })
    server.listen(3000);
    console.log('Server started on http://localhost:3000');
}

exports.startServer = startServer

//app.js
var server = require('./server');

server.startServer();

13. GET和POST发送数据

GET

var http = require('http');
var fs = require('fs');
var url = require('url');
var server = http.createServer(function(request, response){
	console.log('Request received');
	var pathname = url.parse(request.url).pathname;
	console.log(pathname);
	var params = url.parse(request.url, true).query;
	response.writeHead(200, {'Content-Type': 'application/json'});
	response.write(JSON.stringify(params));
	response.end()
})
server.listen(3000);
console.log('Server started on http://localhost:3000');

POST

//index.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h2 style="color:brown;">hpiooi</h2>
    <form action="/post" method="POST">
        姓名:<input type="text" name="name"><br>
        年龄:<input type="text" name="age"><br>
        <input type="submit" value="提交">
    </form>
</body>
</html>
var http = require('http');
var fs = require('fs');
var querystring = require('querystring');
var server = http.createServer(function(request, response){
   console.log('Request received' + request.url);
   if(request.url === '/') {
      response.writeHead(200, {'Content-Type': 'text/html'});
      fs.createReadStream(__dirname + '/index.html').pipe(response);
    }else if(request.url === '/post') {
		var data = "";
		request.on("error", function(err) {
			console.log(err);
		}).on("data", function(chunk){
			data += chunk;
		}).on("end", function(){
			response.writeHead(200, {'Content-Type': 'application/json'});
			response.write(JSON.stringify(querystring.parse(data)));
			response.end();
		})
		
    }
 })
 server.listen(3000);
 console.log('Server started on http://localhost:3000');

14. npm

安装cnpm淘宝镜像

npm install -g cnpm --registry=https://registry.npm.taobao.org

npm init //生成package.json

cnpm install --save express //安装express
//package.json
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.4"
  }
}

15. nodemon

npm i -g nodemon

nodemon app.js
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值