kelichao / node.es6 Goto Github PK
View Code? Open in Web Editor NEWES6新语法特性总结,node.js的使用,npm的使用,日常总结
ES6新语法特性总结,node.js的使用,npm的使用,日常总结
// 引入express模块
var express = require('express');
// 初始化express模块
var app = express();
// 引入静态文件目录
app.use(express.static('dist'));
页面地址输入以下地址即可,dist不用写。
http://localhost:3000/index.html
dist下所有目录都可用
如果你希望所有通过 express.static 访问的文件都存放在一个“虚拟(virtual)”目录(即目录根本不存在)下面,可以通过为静态资源目录指定一个挂载路径的方式来实现,如下所示:
app.use('/static', express.static('public'));
地址写法
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
export命令由于是es6语法,所以在node环境中需要用babel进行转码
// profile.js
// 必须放在全局作用域,不然报错
var name = "Bob";
var age = 23;
export {name, age};
import命令由于是es6语法,所以在node环境中需要用babel进行转码
// main.js
import {name, age} from"./profile";
// import “./profile” 转码之后即为 require("./profile");
// main.js
module circle from "./circle";
// exports只是module.exports的一个辅助方法
// 推荐方式
exports.add = add;
// module.exports是真是存在的东西
// 不推荐
module.exports = add;
npm -v
npm install npm -g
npm list express
$ npm uninstall express
$ npm update express
$ npm init
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
$ cnpm install [name]
http.request(options[, callback])
类似于订阅发布模式,有上限10个
// 引入事件模块
var Event = require("events").EventEmitter;
var life = new Event();
// 添加事件的监听
life.on("testEvent", function(who) {
console.log("给" + who + "倒水");
})
// 触发事件
life.emit("testEvent", "汉子");
// 删除事件
// 注意不能用匿名函数
lift.removeListener("testEvent", funName);
// 删除全部事件
life.removeAllListener("testEvent")
$ npm init
$ npm install express --save
// 引入express模块
var express = require('express');
// 初始化express模块
var app = express();
app.get('/', function (req, res) {
// 返回调用send方法进行输出
res.send('Hello World!');
});
// 监听3000端口
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
$ node app.js
然后在浏览器中打开 http://localhost:3000/ 并查看输出结果
> 主要方法是url.parse(),第一个参数是完整的地址,第二个参数是是否json化query,第三个是是否写死协议
$ node
> url.parse("https:www.baidu.com:8080?abc=123#rou")
Url {
protocol: 'https:',
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: '#rou',
search: '?abc=123',
query: 'abc=123',
pathname: 'www.baidu.com:8080',
path: 'www.baidu.com:8080?abc=123',
href: 'https:www.baidu.com:8080?abc=123#rou'
}
>
拼接方法
url.format({
protocol: 'https:',
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: '#rou',
search: '?abc=123',
query: 'abc=123',
pathname: 'www.baidu.com:8080',
path: 'www.baidu.com:8080?abc=123',
href: 'https:www.baidu.com:8080?abc=123#rou'
})
resolve
url.resolve("https://www.baidu.com/", "/aaa/bbb");
/*
* package.json文件可以手工编写
* 也可以使用npm init命令自动生成
* !!有了package.json文件,直接使用npm install命令,
* 就会在当前目录中安装所需要的模块。!!
*
*
*/
{
// 基本项:项目名称
"name": "Hello World",
// 项目版本
"version": "0.0.1",
// 作者
"author": "张三",
// 描述
"description": "第一个node.js程序"0,
// 关键字
"keywords":["node.js","javascript"],
"repository": {
"type": "git",
"url": "https://path/to/url"
},
"license":"MIT",
"engines": {"node": "0.10.x"},
"bugs":{"url":"http://path/to/bug","email":"[email protected]"},
"contributors":[{"name":"李四","email":"[email protected]"}],
/*
* 指定了项目"运行"所依赖的模块 --save
* 库文件:jquery,react等
*/
"dependencies": {
"express": "latest",
"mongoose": "~3.8.3",
"handlebars-runtime": "~1.0.12",
"express3-handlebars": "~0.5.0",
"MD5": "~1.2.0"
},
/*
* 指定项目"开发"所需要的模块 --save-dev
*/
"devDependencies": {
"bower": "~1.2.8",
"grunt": "~0.4.1",
"grunt-contrib-concat": "~0.3.0",
"grunt-contrib-jshint": "~0.7.2",
"grunt-contrib-uglify": "~0.2.7",
"grunt-contrib-clean": "~0.5.0",
"browserify": "2.36.1",
"grunt-browserify": "~1.3.0",
},
/*
* 用来供插件指定其所需要的主工具的版本。
* 从npm 3.0版开始,peerDependencies不再会默认安装了。
*/
"peerDependencies": {
"chai": "1.x"
},
/*
* bin项用来指定各个内部命令对应的可执行文件的位置。
* 上面代码指定,someTool 命令对应的可执行文件为 bin 子目录下的 someTool.js。
* Npm会寻找这个文件,在node_modules/.bin/目录下建立符号链接。
* 在上面的例子中,someTool.js会建立符号链接npm_modules/.bin/someTool。
* 由于node_modules/.bin/目录会在运行时加入系统的PATH变量,
* 因此在运行npm时,就可以不带路径,直接通过命令来调用这些脚本。
* 因此,像下面这样的写法可以采用简写。
* scripts: {
* start: './node_modules/someTool/someTool.js build'
* }
*
* 简写为
* scripts: {
* start: 'someTool build'
* }
*/
"bin": {
"someTool": "./bin/someTool.js"
},
/*
* 指定运行脚本命令的npm命令缩写
* 例如 npm run start
* "scripts": {
* "start": "node index.js"
* }
*/
"scripts": {
"start": "node index.js"
},
/*main字段指定了加载的入口文件,require('moduleName')就会加载这个文件。
这个字段的默认值是模块根目录下面的index.js。*/
/* config字段用于向环境变量输出值。
*/
}
{
"presets": [],
"plugins": []
}
# 初始化package.json
$ npm init
# ES2015转码规则
$ npm install --save-dev babel-preset-es2015
# react转码规则
$ npm install --save-dev babel-preset-react
{
"presets": [
"es2015",
"react"
],
"plugins": []
}
# 安装
$ npm install --save-dev babel-cli
改写scripts添加build命令
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "babel",
"mybuild": "babel main.js"
},
# main.js是放在根目录的js文件
$ npm run build main.js
# 效果跟上面的语句一样
$ npm run mybuild
// main.js
"use strict";
require("./test.js");// 原本是import语句 import "./test.js"; 被替换了
// 在做这一步引入的时候会
var test = require("./test");
// 两者效果一样 var test = require("./test.js");
console.log(test);
$ npm install --save-dev babel-register
babel-register
// import.js
require("babel-register");
require("./main.js");
console.log("成功执行了main.js中的import语法");
$ cnpm install serialport
var SerialPort = require('serialport');
// COM3视USB安装情况而定
var port = new SerialPort('COM3', function (err) {
if (err) {
return console.log('Error: ', err.message);
}
});
port.write('main screen turn on', function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
port.on('data', function (data) {
console.log('Data:', data);
});
$ node test.js
message written
Data: <Buffer 36 39 35 31 34 39 36 37 30 31 37 39 34 0d 0a>
Data: <Buffer 36 39 35 31 34 39 36 37 30 31 37 39 34 0d 0a>
Data: <Buffer 36 39 35 31 34 39 36 37 30 31 37 39 34 0d 0a>
Data: <Buffer 36 39 35 31 34 39 36 37 30 31 37 39 34 0d 0a>
抓取网页源码
// 引入http包
var http=require('http');
var url = "http://www.imooc.com/learn/348";
http.get(url, function(res) {
var html = "";
res.on("data", function(data) {
html += data
});
res.on("end", function() {
console.log(html);
})
}).on("error", function() {
console.log("搜索出错")
})
列出章节(有错误)
// 引入http包
var http = require('http');
// npm install cheerio安装
// 作用是将html字符解析,用jq的操作方式获取dom中的数据
var cheerio = require("cheerio");
var url = "http://www.imooc.com/learn/348";
function filter(html) {
var $ = cheerio.load(html);
var chapters = $(".learnchapter");
// // 数据格式
// [{
// chapterTitle: "",
// videos: [
// title: "",
// id: ""
// ]
// }]
var courseData = [];
chapters.each(function() {
var chapter = $(this)
var chapterTitle = chapter.find("strong").text();
var videos = chapter.find(".video").children("li");
var chapterData = {
chapterTitle: chapterTitle,
videos: []
};
videos.each(function() {
var video = $(this).find(".studyvideo");
var videoTitle = video.text();
var id = video.attr("href").split("video")[1];
chapterData.videos.push({
title: videoTitle,
id: id
})
});
courseData.push(chapterData);
})
return courseData;
}
http.get(url, function(res) {
var html = "";
res.on("data", function(data) {
html += data
});
res.on("end", function() {
var courseData = filter(html);
//console.log(html);
printCourseInfo(courseData);
})
}).on("error", function() {
console.log("搜索出错")
})
"*.js"
"**/*.js"
/svc/thsft/www/js/lib/kit.js
// 在浏览器中看到的地址
file:///C:/Users/viruser.v-desktop/Desktop/demo/JQ.html
C:\Users\viruser.v-desktop\Desktop\demo\JQ.html
两者的斜杠方向相反
在文件加中新建一个js文件
// 文件名为aaa.js
console.log(123);
用node执行这个js文件
$ node aaa.js
或者用全称的方式,两者效果一样(注:run的方式是在npm中使用才有)
$ node aaa.js
$ npm init
得到
{
"name": "node_demo",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
很多时候我们需要用npm来执行脚本,也就是在scripts里面定义npm脚本命令
{
"scripts": {
"build": "node build.js"
}
}
$ npm run build
# 效果等同于执行
$ node build.js
npm脚本的优点
npm start是npm run start
npm stop是npm run stop的简写
npm test是npm run test的简写
npm install [name]
npm uninstall [name]
server.js
// 引入http包
var http=require('http');
// 启动一个服务
http.createServer(function(req,res){
// 状态码为200,返回的状态,400会报错,但是仍然能看到后台内容
// 第二个参数为返回类型,换成'json/plain'会变成下载内容???!
res.writeHead(200,{'Content-Type':'text/plain'});
// 在页面上输出的内容,
// 但是这个指令经过转码,无法加载html标签
res.end('hello\n<span>大家好</span>');
// 监听端口号为8888
}).listen(8888,'127.0.0.1');
// 控制台输出的日志
console.log('Server running at http://127.0.0.1:8888/');
输入node即可
// 引入express模块
var express = require('express');
// 初始化express模块
var app = express();
// 对网站首页的访问返回 "Hello World!" 字样
// 地址为http://localhost:3000
app.get('/', function (req, res) {
res.send('Hello World!');
});
// /user 节点接受 PUT 请求
// 地址为http://localhost:3000/user
app.get('/user', function (req, res) {
res.send('user');
});
// 监听3000端口
var server = app.listen(3000, function () {});
var express = require("express");
var port = process.env.PORT || 3000;
var app = express();
app.set("views", "./views");
app.set("view engine", "jade");
app.listen(port);
console.log("imooc start port" + port)
// 如果要用4000端口则,windows下无效
//$ PART=4000 node app.js
//添加路由
app.get("/", function(req, res) {
res.render("index", {
title: "imooc 详情页"
})
})
// app.get("/movie/:id", function(req, res) {
// res.render("admin", {
// title: "imooc 管理员页"
// })
// })
// app.get("/admin/movie", function(req, res) {
// res.render("index", {
// title: "imooc 首页"
// })
// })
// app.get("/aaa/", function(req, res) {
// res.render("list", {
// title: "imooc 列表页"
// })
// })
doctype
head
meta(charset="utf-8")
title #{title}
body
h1 #{title}
// 用法一
for (let a = 1;a <=2; a++) {
// 用法二
let c = 123;
}
console.log(a);
console.log(c);
效果类似于在每轮循环内部嵌套了一层匿名函数
var a = [];
for (let i = 0; i< 10; i++) {
a[i] = function() {
console.log(i);
};
}
a[6]();// 输出为6,而不是10;
{{{{{{let a=123}}}}}}
npm install express
npm install jade
npm install mongoose
npm install bower -g
bower install bootstrap
基于 Node.js 平台的 web 应用开发框架官网
源于 Node.js 的 HTML 模板引擎
mongoDB框架
npm 是伴随Node.js 出现的一个包管理器,最开始只能支持 Node.js 的模块管理,但是后来, npm 官网经过一次改版,打出的口号是,javascript 的包管理器,所以,其已经不在局限于是Node.js 的模块管理了,已经通用到了所有 js 的包管理工具了,可以说,前后通吃了。
bower 的话,从一开始,就是专门为前端表现设计的包管理器,一切全部为前端考虑的。npm 和bower 的最大区别,就是 npm 支持嵌套地依赖管理,而 bower只能支持扁平的依赖(嵌套的依赖,由程序员自己解决)。
为什么有很多项目 bower 和 npm 都用呢,那是因为要用 bower 管理前端的包,而用 npm 去管理一些后端的包和构建工具,例如,yeoman,grunt,gulp,jshint 等等等等。
前端响应式框架
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.