1. 介绍 node是javaScript的运行环境,可以解析和执行javaScript代码
node没有BOM和DOM,只有EcmaScript
node特性:事件驱动;非阻塞的I/O模型;轻量高效
2. npm npm是node的包管理工具;用来管理javaScript相关的包
因为npm默认镜像地址是国外地址,所以改成国内的淘宝镜像
npm config set registry https://registry.npm.taobao.org
npm install -g全局安装 –save/-S生产环境 -dev/-D开发环境
3. 核心模块 3.1 读写文件 var fs = require ('fs' );fs.readFile ('./demo.html' ,function (error,data ) { console .log (error); console .log (data.toString ()); }) fs.writeFile ('./demo.html' ,'写入的东西' ,function (error ) { console .log (error); console .log (data.toString ()); }) fs.readdir ('./node' ,function (error,data ) { console .log (error); console .log (data); })
3.2 http服务 四步走:
加载http核心模块
创建一个Web服务器
注册request请求事件
绑定端口号,启动服务器
var http = require ('http' );var sever = http.createServer ();sever.on ('request' ,function (request,response ) { console .log ('注册请求事件' ); }) server.listen (3000 ,function ( ) { console .log ('请求成功了访问:localhost:3000' ); }) http.createServer ().on ('request' ,function (request,response ) { console .log ('注册请求事件' ); }).listen (3000 ,function ( ) { console .log ('请求成功了访问:localhost:3000' ); })
3.3 模板引擎art-template 第三方node模块
template (filename, data);template.compile (source, options); template.render (source, data, options);
{{if value}} ... {{/if}} {{if v1}} ... {{else if v2}} ... {{/if}} {{each target}} {{$index}} {{$value}} {{/each}} <% for (var i = 0; i < target.length; i++) { %> <%= i %> <%= target[i] %> <% } %>
target
是一个数组,each
用于对数组遍历,$index
是数组的下标, $value
是数组的值
浏览器下使用(单html文件)
<script src ="https://npm.elemecdn.com/[email protected] /lib/template-web.js" > </script > <body > <div id ="container" > </div > </body > <script type ="text/html" id ="tpl" > {{if user}} <h2 > {{user.name }} </h2 > {{/if }} </script > <script > var user = { name : 'Template username' } var html = template ('tpl' , {user : user}) var container = document .querySelector ('#container' ); container.innerHTML = html; </script >
node下使用
html文件
<tbody > {{each commentsList}} <tr > <td > <span > {{$value.name}}</span > </td > </tr > {{/each}} </tbody >
外部js文件
let result = [{name :vivy},{name :violet},{name :hitaki}]let html = template.render (data.toString (), { commentsList : results})
3.4 mysql 引入流程
var connection = mysql.createConnection ({ host : 'localhost' , user : 'root' , password : 'kkk' , database : 'comment' }); connection.connect (); let sql = 'SELECT * FROM comments' ;connection.query (sql, function (error, results ) { if (error) throw error; console .log (results); }); connection.end ();
sql增删改查语句
selelt * from table ;/ / 查询所有 insert into table (id,name) values (1 ,'vivy' );/ / 插入数据delete from table where id = 1 ;/ / 删除数据update table set id = 2 , name = 'vivy' where id = 1 ;/ / 修改数据