nodejs-基础
目录
01-nodejs介绍
1.什么是nodejs
1.(javascript跑在机器端,服务端)Javascript on the machine
2.(跑在谷歌v8引擎上)A runtime for Google Chrome's V8 Javascript engine
2.nodejs的使用
1.构建工具(gulp,webpack都要依赖nodejs)Build Tools and Utilities
2.(web应用,web服务端)Web Applications / Web Services
3.nodejs擅长做什么
1.轻量级到大型应用 Lightweight Applications all the way up to very large
2.高并发性 High Concurrency
3.异步 Asyncronous Actions/Requests/non-blocking
4.实时 Realtime Communication
5.同构应用Isomorphic Applications - shared code between server and client
02rounning-files
1.安装
app.js
'use strict';
//process.argv 接受变量
var command = process.argv[2];
var a = Number(process.argv[3]);
var b = Number(process.argv[4]);
if (command === 'add') {
console.log(a+b);
} else if (command === 'sub'){
console.log(a-b);
} else if (command === 'mul'){
console.log(a*b);
}
CMD运行
node app.js add 1 2 //3
node app.js sub 1 2 //-1
node app.js mul 1 2 //2
03-commonjs-moudules
1.首先建一个math.js
exports.add = function(a, b){
return a + b;
}
exports.sub = function(a, b){
return a - b;
}
exports.mul = function(a, b){
return a * b;
}
2.然后建一个app.js 引人math.js
var math = require('./math');
console.log(math);//{ add: [Function], sub: [Function], mul: [Function] }
var command = process.argv[2];
var a = Number(process.argv[3]);
var b = Number([process.argv[4]]);
var value = math[command](a, b);
console.log(value);//node app.js mul 1 2 结果为2
04-npm-moudulers
建立package.json
npm init
下载包
npm install axios
npm install lodash
下载包,并加到package里面
npm install axios -S
npm install lodash -S
axios使用介绍传送门
lodash使用介绍传送门
建app.js
var _ = require('lodash');
var axios = require('axios');
axios.get('http://rest.learncode.academy/api/myuser/friends').then((res) => {
console.log(res.data);
var jake = _.find(res.data, {name: "Jake"});
console.log(jake);//{ name: 'Jake', age: '32', id: '57766a9a4a9cb90100bf16ec' }
})
05-npm script
简单介绍
scripts里面的
"start": "node app"
npm run start 相当于 node app
{
"name": "5-npm-scripts",
"version": "1.0.0",
"description": "",
"main": "app.js",
"dependencies": {},
"devDependencies": {
"nodemon": "^1.9.2"
},
"scripts": {
"start": "node app",
"dev": "nodemon app",
"test": "node test",
"test-watch": "nodemon test"
},
"author": "",
"license": "ISC"
}
更加详细的介绍,建议看阮一峰的scripts介绍
nodemon
这个可以监控js变化
eg
app.js
'use strict';
var math = require('./math');
var value = math.add(5, 6);
console.log(value);
math.js
exports.add = function(a, b) {
return a + b;
}
exports.subtract = function(a, b) {
return a - b;
}
exports.multiply = function(a, b) {
return a * b;
}
test.js
'use strict';
var assert = require('assert');
var math = require('./math');
assert(math.add(3, 4) === 7);
assert(math.subtract(3, 4) === -1);
assert(math.multiply(3, 4) === 12);
console.log("all tests passed!");
06-base-webserver
创建server.js
'use strict';
//http模块
var http = require('http');
//封装的方法
var handlers = require('./handlers');
//创建服务
var server = http.createServer(function(request, response) {
//url地址
var url = request.url;
if(url === '/'){
handlers.homepage(request, response);
}else if (url === "/profile") {
handlers.profile(request, response);
} else {
handlers.notFound(request, response);
}
});
//端口3000
server.listen(3000);
console.log('start 3000');
handlers.js
'use strict';
//首页
exports.homepage = function(request, response){
response.setHeader('Content-Type', 'text/html');
response.end('<h1>helloworld</h1>')
}
//一个接口
exports.profile = function(request, response){
var profile = {
name : 'will',
age : 35
}
response.setHeader('Content-Type','application/json');
response.end(JSON.stringify(profile));
}
//404
exports.notFound = function(request, response) {
response.statusCode = 404;
response.setHeader("Content-Type", "text/html");
response.end("<h1>404 Not Found!</h1>");
}
07-es6
1.下载babel-register
npm install babel-register -S
2.下载babel-preset-es2015
npm install babel-preset-es2015 --save-dev
main.js
require('babel-register');
require('./src/server');
server.js
import http from 'http';
import { homepage, notFound } from './handlers';
const server = http.createServer((request, response) =>{
homepage(request, response);
});
server.listen(3000);
console.log('listen 3000');
handlers.js
export function homepage(request, response){
response.setHeader("Content-Type", "text/html");
response.end("hello world");
}
export function notFound(request, response){
response.setHeader("Content-Type", "text/html");
response.end("404");
}
08-express
express 简单介绍
下载express
npm install express -S
简单的例子
const express = require('express');
//引入express
const app = express();
//链式结构,中间件,必须要有next才能执行下一步
app
.use((req, res, next) => {
var profile = {name: "will"};
req.profile = profile;
next();
})
.get("/", (req, res) => {
res.send(req.profile);
})
//监听端口3000
app.listen(3000);
console.log('listen 3000');
09-routes的使用
新建一个users.js,然后app.use使用这个中间件
const users = require('./routes/users');
app.use('/users', users);
users.js
const express = require('express');
const router = express.Router();
router
.get("/", (req, res) => {
res.send(users);
})
.get("/:id", (req, res) => {
const { id } = req.params;
const user = users.find(user => user.id == id)
if (user) {
res.send(user);
} else {
res.status(404).send(`User ${id} does not exist`);
}
})
.delete('/:id', (req, res) => {
const { id } = req.params;
const index = users.findIndex(user => user.id == id);
if (index > -1){
users.splice(index, 1);
res.sendStatus(200);
} else {
res.status(404).send(`User ${id} does not exist`);
}
});
module.exports = router;
var users = [{
"id": 1,
"first_name": "Gregory",
"last_name": "Garcia",
"email": "ggarcia0@list-manage.com",
"gender": "Male",
"ip_address": "23.180.99.244"
}]
10-static静态文件
下载serve-favicon
npm install serve-favicon -S
静态文件
const staticAssets = __dirname + '/public';
ico地址
const favicon = require('serve-favicon');
const faviconPath = __dirname + '/public/favicon.ico';
使用
app
.use(express.static(staticAssets))
.use(favicon(faviconPath))
完整代码
const express = require('express');
const favicon = require('serve-favicon');
const app = express();
//静态文件
const staticAssets = __dirname + '/public';
//ico地址
const faviconPath = __dirname + '/public/favicon.ico';
app
.use(express.static(staticAssets))
.use(favicon(faviconPath))
.get('/api/profile', (req, res) => {
var profile = {name: 'will'};
res.send(profile);
});
app.listen(3000);
11-hjs模板引入
下载hjs
npm install hjs -S
express中引入
app
.set("views", __dirname + "/views")
.set('view engine', 'hjs')
渲染
var title = "still another title";
var tweets = [
"my first tweet",
"other tweet",
"yet another tweet",
];
res.render('index', {
title: title,
tweets: tweets,
showTweets: true,
//模板替換,公用的
partials: {header: "header", tweets: "tweets"}
})
views/header.hjs
<h1>title</h1>
views/tweets.hjs
<ul>
{{#tweets}}
<li>{{.}}</li>
{{/tweets}}
</ul>
views/index.hjs
<html>
<head>
<link rel="stylesheet" href="/css/main.css">
</head>
<body>
{{> header}}
{{#showTweets}}
{{> tweets}}
{{/showTweets}}
<script src="/js/main.js"></script>
</body>
</html>
server.js完整代码
'use strict';
const express = require('express');
const favicon = require('serve-favicon');
const app = express();
const staticAssets = __dirname + '/public';
//const faviconPath = __dirname + '/public/favicon.ico';
app
.set("views", __dirname + "/views")
.set('view engine', 'hjs')
.use(express.static(staticAssets))
//.use(favicon(faviconPath))
.get('/', (req, res) => {
var title = "still another title";
var tweets = [
"my first tweet",
"other tweet",
"yet another tweet",
];
res.render('index', {
title: title,
tweets: tweets,
showTweets: true,
//模板替換,公用的
partials: {header: "header", tweets: "tweets"}
})
});
app.listen(3000);
console.log('listen 3000');
12-mysql
连接mysql数据库,终于到了这步。
mysql 下载
npm install mysql -S
knex下載 knex传送门
npm install knex -S
链接mysql
const db = knex({
client: 'mysql',
connection: {
host: '127.0.0.1',
user: 'root',
database: 'test_node',
password: 'youpassword'
}
})
完整代码(这里是用RESTful)
const express = require('express');
const bodyParser = require('body-parser');
const knex = require('knex');
const db = knex({
client: 'mysql',
connection: {
host: '127.0.0.1',
user: 'root',
database: 'test_node',
password: 'youpassword'
}
})
// GET /users 获取所有用户
// GET /user/:id 获取id
// POST /users 创建用户
// PUT /users/:id 更新用户
// DELETE /users/:id 删除用户
express()
.use(bodyParser.json())
.get('/users', (req, res, next) => {
db('users').then((users) => {
res.send(users);
}, next)
})
.post('/users', (req, res, next) => {
db('users')
.insert(req.body)
.then((userIds) =>{
res.send(userIds)
}, next)
})
.get('/users/:id', (req, res, next) => {
const { id } = req.params;
db('users')
.where('id', id)
.first()
.then((users)=>{
if(!users){
return res.send(400);
}
res.send(users)
}, next)
})
.put('/users/:id', (req, res, next) => {
const { id } = req.params;
db('users')
.where('id', id)
.update(req.body)
.then((result) => {
if(result === 0){
return res.send(400)
}
res.send(200)
}, next)
})
.delete('/users/:id', (req, res, next) => {
const { id } = req.params;
db('users')
.where('id', id)
.delete()
.then((result) => {
if(result === 0){
return res.send(400)
}
res.send(200)
}, next)
})
.listen(3000)
console.log('listen 3000');
代码在github上,如果觉得有帮助请给我星星
nodejs-基础的更多相关文章
- [转]Nodejs基础中间件Connect
Nodejs基础中间件Connect 从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发.Nodejs框架是基于V8的引擎,是目前速度最快的J ...
- Nodejs基础中间件
Nodejs基础中间件Connect http://www.tuicool.com/articles/emeuie 关于作者 张丹(Conan), 程序员Java,R,PHP,Javascript ...
- Nodejs第一天-{Nodejs基础 深刻理解浏览器 环境变量 基础语法}
Nodejs第一天 1.什么是Nodejs Nodejs是一个可以运行(解析)ECMAScript的环境; ECMAScript是规定了一些列的语法 ,这些语法想要解析的执行就需要放在某个环境 ...
- nodejs 基础篇整合
nodeJs 基础篇整合 最近有朋友也想学习nodeJs相关方面的知识,如果你是后端想接近前端,node作为一门跑在服务端的JS语言从这里入门再好不过了.如果你正好喜欢前端,想走的更高,走的更远.no ...
- 前端知识体系-NodeJS相关】NodeJS基础知识全面总结
NodeJS基础知识 1. Node的全局对象和全局变量 1.1 全局对象:所有模块都可以调用的 global:表示Node所在的全局环境,类似于浏览器的window对象. process:该对象表示 ...
- Nodejs基础中间件Connect
http://www.tuicool.com/articles/emeuie 关于作者 张丹(Conan), 程序员Java,R,PHP,Javascript weibo:@Conan_Z blog: ...
- 02 nodejs命令参数(NodeJS基础入门)
声明:本文章可供有一定js基础的朋友参考nodejs入门,本文未讲解nodejs的安装,如有需要的同学可以加QQ3382260752找我,进行交流学习. 建议使用开发软件:webstorm或hbuil ...
- nodejs基础教程回顾01
最近在复习nodejs,因为框架太多隔一段时间不用就会忘了,所以没办法必须时常拿出来练练,就像家里有好几辆车,要时不常的轮流开一圈.我就从最基础的开始写,怎么下载安装就不说了,首先是nodejs的三类 ...
- NodeJS基础总结(一)
NodeJS官网网址:https://nodejs.org/en/ 使用require方法加载fs核心模块 var fs = require('fs'); 一.读取文件// 第一个参数就是尧读取的 ...
- NodeJS基础教程
关于 本书致力于教会你如何用Node.js来开发应用,过程中会传授你所有所需的“高级”JavaScript知识.本书绝不是一本“Hello World”的教程. 状态 你正在阅读的已经是本书的最终版. ...
随机推荐
- Codeforces Round #419 (Div. 2)
1.题目A:Karen and Morning 题意: 给出hh:mm格式的时间,问至少经过多少分钟后,该时刻为回文字符串? 思路: 简单模拟,从当前时刻开始,如果hh的回文rh等于mm则停止累计.否 ...
- .NET Core程序中使用User Secrets存储敏感数据
前言 在开发中经常会用到一些敏感数据,比如AppSecret或数据库连接字符串,无论是硬编码还是写在配置文件中,最终都要push到svn或git上.对于开源项目,这些敏感数据就无隐私可言了,对于私有项 ...
- 详解 RAC 中各种IP和监听的意义
一.SCAN 概念 SCAN(Single Client Access Name)是 Oracle从11g R2开始推出的,客户端可以通过 SCAN 特性负载均衡地连接到 RAC数据库 SCAN 最明 ...
- Jquery DataTables 使用AJAX POST的问题
最近项目在用需要用表格,听说DataTables很好很强大,于是用了一下. Get请求没什么问题,问题处在POST请求上 Jquery原生的POST请求没有问题,代码如下 $.ajax({ url ...
- ASP.NET MVC Bundling and RequireJS
关于ASP.NET MVC Bundling and RequireJS的取舍问题,最近比较困惑,我希望有一种方式可以结合两者的优点.作为.NET程序员,难道你没有过这方面的困惑吗? 因为我感觉各自都 ...
- 【Android Developers Training】 87. 序言:同步到云
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 【Android Developers Training】 65. 应用投影和相机视图
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- 在SOUI中使用网格布局
在实现网格布局前,SOUI支持两种布局形式:相对布局,和线性布局,其中线性布局是2017年2月份才支持的布局. 这两年工作都在Android这里,Android里有号称5大布局(RelativeLay ...
- VB6之WebBrowser控件
UI短手或者GDI+用烦的童鞋可以借用WebBrowser打造漂亮的程序界面,只需要下载一个好看点的html代码就够了. 引用: Microsoft Html Object Library 部件: M ...
- (转载)oracle 在一个存储过程中调用另一个返回游标的存储过程
原文链接:http://www.jb51.net/article/20160.htm 实际项目当中经常需要在一个存储过程中调用另一个存储过程返回的游标,本文列举了两种情况讲述具体的操作方法. 第一种情 ...