h264-live-player代码学习与注解(二):server-rpi.js
"use strict";
/**
* Run this on a raspberry pi
* then browse (using google chrome/firefox) to http://[pi ip]:8080/
*/
const http = require('http');
const express = require('express');
const WebStreamerServer = require('./lib/raspivid');
const app = express();
//public website
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/vendor/dist'));
const server = http.createServer(app);
const silence = new WebStreamerServer(server);
server.listen(8080);
1.使用 “use strict” 指令
“use strict” 指令在 JavaScript 1.8.5 (ECMAScript5) 中新增。
它不是一条语句,但是是一个字面量表达式,在 JavaScript 旧版本中会被忽略。
“use strict” 的目的是指定代码在严格条件下执行。
严格模式下你不能使用未声明的变量。
2.require命令
用于引入模块、 JSON、或本地文件。
可以从 node_modules 引入模块。 可以使用相对路径(例如 ./、 ./foo、 ./bar/baz、 …/foo)引入本地模块或 JSON 文件,路径会根据 __dirname 定义的目录名或当前工作目录进行处理。
例子:
// 引入本地模块:
const myLocalModule = require('./path/myLocalModule');
// 引入 JSON 文件:
const jsonData = require('./path/filename.json');
// 引入 node_modules 模块或 Node.js 内置模块:
const crypto = require('crypto');
3.express模块
Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具。
使用 Express 可以快速地搭建一个完整功能的网站。
app.get和app.use,app.all注册路由:
app.get注册路由:
请求方法必须是get方法,而且路径是严格匹配的(忽略url后面拼接的参数,例如?name=123这类)
app.use注册路由:
不限定请求的方法,get/post等都可以
路径模糊匹配,这个路径和他路径下的子路径都可以匹配
app.use('/item', function (req, res) {
res.send('itemPage');
})
//http://localhost:8080/item 成功
//http://localhost:8080/item/233 成功
//http://localhost:8080/item?name=hello 成功
//http://localhost:8080/123/item 失败
//http://localhost:8080/item233 失败
4.express.static
在使用express框架的时候,会遇到设置静态文件目录,代码如下:
//将静态文件目录设置为:项目根目录+/public
app.use(express.static(__dirname + '/public'));
//或者
app.use(express.static(path.join(__dirname, 'public')));
express 会在静态资源目录下查找文件,所以不需要把静态目录public作为url的一部分。现在,你可以加载 public目录下的文件了:
http://localhost:3000/hello.html
http://localhost:3000/images/1.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/index.js
5.server = http.createServer(app);
函数原型:http.createServer([requestListener])
http函数用来创建一个HTTP服务器,并将 requestListener 作为 request 事件的监听函数。
简单用法:
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);
可以看到,传入的其实是一个function
之前我们调用的express()其实是返回了一个名为app的function对象,我们正好把他们塞进http.createServer中。