Node.js 极简笔记

Node.js

一.Node基础

概念:Javascript运行时平台,不是语言,也不是框架,是一个平台。javascript

1.1 what is node ?

  • Node.js 是一个基于Chrome V8 引擎的JavaScript运行环境
  • Node.js使用了一个事件驱动、非阻塞式I/O的模型,使其轻量又高效
  • Node.js的包管理工具npm,是全球最大的开源库生态系统
  • 官网 http://nodejs.cn/
  • npm 插件官网:https://www.npmjs.com/

1.2做用

1.3为何学习?

1.4 常见问题

  • Python环境丢失
  • Node中有些第三方的包是以C/C++源码的方式发布的,须要安装后编译,确保全局环境中可使用python命令,python 版本推荐2.7.0
  • 环境变量丢失
  • 部分电脑安装完毕以后没有环境变量须要手动配置
  • Windows中环境变量分为系统变量和用户变量
  • 环境变量的变量名是不区分大小写的
  • PATH 变量:只要添加到 PATH 变量中的路径,均可以在任何目录下
  • 目的能够在任何地方调起node命令

1.4 案例:操做步骤

Hello.jscss

1.编写js文件html

2.定位到目录vue

3.输入node xxx.js,解释执行java

let str="hello world"console.log(str)console.log(window)  //没有bomconsole.log(document) //没有dom12345

多出来的功能:node

//1.定义导入包
let fs=require('fs')
//2.读取hello.js
//参数:路径,匿名函数
fs.readFile('hello.js',function (error,data) {
	console.log(data);//utf-8编码
    console.log(data.toString());  //格式能够输出 
})12345678

输出的格式不是ASCI编码格式,注意!!!python

关于参数的代码理解android

//1.定义导入包let fs=require('fs')//2.读取hello.js//参数:路径,匿名函数fs.readFile('hello2.js',function (error,data) {
    // if(error==null)
    //     console.log('没有错误')
    if(error)
        console.log('读取文件失败!')
    else
        console.log(data.toString());})123456789101112

1.5 http服务

//1.导入http包let http=require('http')//2.定义server变量,返回一个server实例;let server=http.createServer()//3.服务器的响应,接受request请求,产生会回调事件server.on('request',function () {
    console.log('接受来自客户端的请求....')})//4.绑定到响应的端口号;server.listen(3000,function () {
    console.log('服务器启动了,能够经过http://localhost:3000/来访问...')})123456789101112
//1.导入http包let http=require('http')//2.定义server变量,返回一个server实例;let server=http.createServer()//3.服务器的响应,接受request请求,产生会回调事件//增长参数:request、responseserver.on('request',function (request,response) {
    console.log('接受来自客户端的请求....')
    console.log('请求路径是:'+request.url)
    //response:响应输出;服务器发送给客户端
    response.write('你好')
    response.write('test...aaa')
    response.end()})//4.绑定到响应的端口号;server.listen(3000,function () {
    console.log('服务器启动了,能够经过http://localhost:3000/来访问...')})123456789101112131415161718

根据不一样的url返回不一样的服务git

let url=request.urlgithub

url返回的是/以后的路径

//1.导入http包let http=require('http')//2.定义server变量,返回一个server实例;let server=http.createServer()//3.服务器的响应,接受request请求,产生会回调事件//增长参数:request、responseserver.on('request',function (request,response) {
    console.log('接受来自客户端的请求....')
    console.log('请求路径是:'+request.url)
    //3.1获取请求的url路径信息;
    let url=request.url
    console.log('----'+url)
    //接下来,根据url进行判断;
    if(url=='/'){
        response.end('index.html')
    }else if(url=='/login'){
        response.end('login.html')
    }else if(url=='/products'){
        let products=[
            {name:'苹果',price:4.5},
            {name:'香蕉',price:3.5},
            {name:'橘子',price:2.5}]
        response.end(JSON.stringify(products))
    }
    else{
        response.end('404 Error')
    }
    //response:响应输出;服务器发送给客户端
    // response.write('你好')
    // response.write('test...aaa')
    // response.end()})//4.绑定到响应的端口号;server.listen(3000,function () {
    console.log('服务器启动了,能够经过http://localhost:3000/来访问...')})123456789101112131415161718192021222324252627282930313233343536

二.模块

模块分为三种:

  1. 内置模块
  2. 自定义模块
  3. 第三方模块

2.1 内置模块

以前代码require(‘fs’)就是引用的内置模块。Node为JS提供了不少服务器级别的API,这些API绝大多数都被包装到了一个有名字的核心模块。例如文件操做的fs模块。

使用格式:

let 变量名=require(‘模块名’) //fs:文件读写模块

let http=require(‘http’) //http:协议模块;

let path=require(‘path’) //路径处理模块

let os=require(‘os’)

let fs=require(‘fs’)

2.1.1.文件夹的操做

let fs = require("fs");//建立文件夹//fs.mkdir('./hello',(err,data)=>{// console.log(err);// console.log(data);//});//修改文件夹//fs.rename('./hello','./testyyh',(err)=>{// if(err){//    console.log("error");// }else{//    console.log("ok");// }//});//删除文件夹-->只能删除空文件夹fs.rmdir('./testyyh',(err)=>{
    if(err){
        console.log('删除失败');
        console.log(err);
    }else{
        console.log('ok');
    }1234567891011121314151617181920212223

2.1.2 文件的操做

const   fs = require('fs');//建立文件,覆盖写入,正常的话则是追加//fs.writeFile('test.txt','这是个人第一个文件',(err)=>{// if(err){//    console.log('建立失败');//    console.log(err);// }else{//    //    console.log('建立成功!');// }// //});//读取文件,在原来的基础上追加文件//fs.appendFile('test.txt','韩梅梅你好',(err)=>{// console.log(err);//});//读取文件这是第一种方式//fs.readFile('test.txt',(err,msg)=>{// console.log(err);// console.log(msg.toString("utf8"));//在转化为字符串的时候指定编码方式//});//在参数中指定编码方式//fs.readFile('test.txt','utf8',(err,msg)=>{// // console.log(err);// console.log(msg);//});//删除文件//fs.unlink('./test.txt',(err)=>{// console.log(err);//});1234567891011121314151617181920212223242526272829303132

2.1.3 判断是文件仍是目录

const fs = require('fs');fs.readdir('./',(err,dirs)=>{
    for(let index=0;index<dirs.length;index++){
        console.log(dirs[index]);
    }});fs.stat('./',(err,stats)=>{
    if(stats.isFile()){

        console.log('是一个文件');
    }else{
        console.log('是一个目录');
    }});1234567891011121314

2.2 自定义模块

详细介绍自定义模块:

建立一个模块(一个js文件就是一个模块),这是test.js

let hellomodule={
    sayhell(){
        console.log("hello world");
    }}module.exports=hellomodule123456

在另一个文件进行调用

//1.导入文件;必须是./的模式,直接路径不可用;let testModule=require('./module.js')//2.直接使用;console.log(testModule)testModule.sayhell()12345

2.3 操做系统

//1.引用os核心模块let os=require('os')//2.输出cpu的信息;console.log(os.cpus())//内存信息console.log(os.totalmem())console.log(os.type)//.1.1引用path核心模块let path=require('path')//2.测试path;path.extname('c:/soft/oop.java')//ext:扩展名console.log(path.extname('c:/soft/oop.java'))123456789101112131415
//输出端口号;console.log('请求端口号:'+request.socket.remotePort)console.log('请求地址:'+request.socket.remoteAddress)123

2.4 http+箭头函数

let http=require('http')let server=http.createServer()server.on('request',(req,resp)=>{
    console.log('请求地址:'+req.url)
    console.log('请求客户端地址信息:'+req.socket.remotePort,req.socket.remoteAddress)

    resp.end('hello world.张晨光...')})server.listen(5000,()=>{
    console.log('服务器启动能够访问了...')})1234567891011121314

能够启动多个服务,端口号不一样就行!!!

2.5 发送文件内容

let http=require('http')let fs=require('fs')let server=http.createServer()server.on('request',(req,resp)=>{
    let url=req.url    if(url==='/'){
        fs.readFile('./hello.html',(err,data)=>{
            if(err){
                resp.setHeader('Content-Type','text/plain;charset=utf-8')
                resp.end('文件读取失败!')
            }else{
                resp.setHeader('Content-Type','text/html;charset=utf-8')
                resp.end(data)
            }
        })
    }})server.listen(3000,()=>{
    console.log('服务器启动能够访问了...')})1234567891011121314151617181920212223

能够读取图片的程序升级

let http=require('http')let fs=require('fs')let server=http.createServer()server.on('request',(req,resp)=>{
    let url=req.url    if(url==='/'){
        fs.readFile('./hello.html',(err,data)=>{
            if(err){
                resp.setHeader('Content-Type','text/plain;charset=utf-8')
                resp.end('文件读取失败!')
            }else{
                resp.setHeader('Content-Type','text/html;charset=utf-8')
                resp.end(data)
            }
        })
    }
    else if(url==='/photo'){
        fs.readFile('./resources/2a.jpg',(err,data)=>{
            if(err){
                resp.setHeader('Content-Type','text/plain;charset=utf-8')
                resp.end('图片读取失败!')
            }else{
                resp.setHeader('Content-Type','image/jpeg')
                resp.end(data)
            }
        })
    }})server.listen(3000,()=>{
    console.log('服务器启动能够访问了...')})12345678910111213141516171819202122232425262728293031323334

Http Mime Type

文件扩展名 Content-Type(Mime-Type) 文件扩展名 Content-Type(Mime-Type)
.*( 二进制流,不知道下载文件类型) application/octet-stream .tif image/tiff
.001 application/x-001 .301 application/x-301
.323 text/h323 .906 application/x-906
.907 drawing/907 .a11 application/x-a11
.acp audio/x-mei-aac .ai application/postscript
.aif audio/aiff .aifc audio/aiff
.aiff audio/aiff .anv application/x-anv
.asa text/asa .asf video/x-ms-asf
.asp text/asp .asx video/x-ms-asf
.au audio/basic .avi video/avi
.awf application/vnd.adobe.workflow .biz text/xml
.bmp application/x-bmp .bot application/x-bot
.c4t application/x-c4t .c90 application/x-c90
.cal application/x-cals .cat application/vnd.ms-pki.seccat
.cdf application/x-netcdf .cdr application/x-cdr
.cel application/x-cel .cer application/x-x509-ca-cert
.cg4 application/x-g4 .cgm application/x-cgm
.cit application/x-cit .class java/*
.cml text/xml .cmp application/x-cmp
.cmx application/x-cmx .cot application/x-cot
.crl application/pkix-crl .crt application/x-x509-ca-cert
.csi application/x-csi .css text/css
.cut application/x-cut .dbf application/x-dbf
.dbm application/x-dbm .dbx application/x-dbx
.dcd text/xml .dcx application/x-dcx
.der application/x-x509-ca-cert .dgn application/x-dgn
.dib application/x-dib .dll application/x-msdownload
.doc application/msword .dot application/msword
.drw application/x-drw .dtd text/xml
.dwf Model/vnd.dwf .dwf application/x-dwf
.dwg application/x-dwg .dxb application/x-dxb
.dxf application/x-dxf .edn application/vnd.adobe.edn
.emf application/x-emf .eml message/rfc822
.ent text/xml .epi application/x-epi
.eps application/x-ps .eps application/postscript
.etd application/x-ebx .exe application/x-msdownload
.fax image/fax .fdf application/vnd.fdf
.fif application/fractals .fo text/xml
.frm application/x-frm .g4 application/x-g4
.gbr application/x-gbr . application/x-
.gif image/gif .gl2 application/x-gl2
.gp4 application/x-gp4 .hgl application/x-hgl
.hmr application/x-hmr .hpg application/x-hpgl
.hpl application/x-hpl .hqx application/mac-binhex40
.hrf application/x-hrf .hta application/hta
.htc text/x-component .htm text/html
.html text/html .htt text/webviewhtml
.htx text/html .icb application/x-icb
.ico image/x-icon .ico application/x-ico
.iff application/x-iff .ig4 application/x-g4
.igs application/x-igs .iii application/x-iphone
.img application/x-img .ins application/x-internet-signup
.isp application/x-internet-signup .IVF video/x-ivf
.java java/* .jfif image/jpeg
.jpe image/jpeg .jpe application/x-jpe
.jpeg image/jpeg .jpg image/jpeg
.jpg application/x-jpg .js application/x-javascript
.jsp text/html .la1 audio/x-liquid-file
.lar application/x-laplayer-reg .latex application/x-latex
.lavs audio/x-liquid-secure .lbm application/x-lbm
.lmsff audio/x-la-lms .ls application/x-javascript
.ltr application/x-ltr .m1v video/x-mpeg
.m2v video/x-mpeg .m3u audio/mpegurl
.m4e video/mpeg4 .mac application/x-mac
.man application/x-troff-man .math text/xml
.mdb application/msaccess .mdb application/x-mdb
.mfp application/x-shockwave-flash .mht message/rfc822
.mhtml message/rfc822 .mi application/x-mi
.mid audio/mid .midi audio/mid
.mil application/x-mil .mml text/xml
.mnd audio/x-musicnet-download .mns audio/x-musicnet-stream
.mocha application/x-javascript .movie video/x-sgi-movie
.mp1 audio/mp1 .mp2 audio/mp2
.mp2v video/mpeg .mp3 audio/mp3
.mp4 video/mpeg4 .mpa video/x-mpg
.mpd application/vnd.ms-project .mpe video/x-mpeg
.mpeg video/mpg .mpg video/mpg
.mpga audio/rn-mpeg .mpp application/vnd.ms-project
.mps video/x-mpeg .mpt application/vnd.ms-project
.mpv video/mpg .mpv2 video/mpeg
.mpw application/vnd.ms-project .mpx application/vnd.ms-project
.mtx text/xml .mxp application/x-mmxp
.net image/pnetvue .nrf application/x-nrf
.nws message/rfc822 .odc text/x-ms-odc
.out application/x-out .p10 application/pkcs10
.p12 application/x-pkcs12 .p7b application/x-pkcs7-certificates
.p7c application/pkcs7-mime .p7m application/pkcs7-mime
.p7r application/x-pkcs7-certreqresp .p7s application/pkcs7-signature
.pc5 application/x-pc5 .pci application/x-pci
.pcl application/x-pcl .pcx application/x-pcx
.pdf application/pdf .pdf application/pdf
.pdx application/vnd.adobe.pdx .pfx application/x-pkcs12
.pgl application/x-pgl .pic application/x-pic
.pko application/vnd.ms-pki.pko .pl application/x-perl
.plg text/html .pls audio/scpls
.plt application/x-plt .png image/png
.png application/x-png .pot application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint .ppm application/x-ppm
.pps application/vnd.ms-powerpoint .ppt application/vnd.ms-powerpoint
.ppt application/x-ppt .pr application/x-pr
.prf application/pics-rules .prn application/x-prn
.prt application/x-prt .ps application/x-ps
.ps application/postscript .ptn application/x-ptn
.pwz application/vnd.ms-powerpoint .r3t text/vnd.rn-realtext3d
.ra audio/vnd.rn-realaudio .ram audio/x-pn-realaudio
.ras application/x-ras .rat application/rat-file
.rdf text/xml .rec application/vnd.rn-recording
.red application/x-red .rgb application/x-rgb
.rjs application/vnd.rn-realsystem-rjs .rjt application/vnd.rn-realsystem-rjt
.rlc application/x-rlc .rle application/x-rle
.rm application/vnd.rn-realmedia .rmf application/vnd.adobe.rmf
.rmi audio/mid .rmj application/vnd.rn-realsystem-rmj
.rmm audio/x-pn-realaudio .rmp application/vnd.rn-rn_music_package
.rms application/vnd.rn-realmedia-secure .rmvb application/vnd.rn-realmedia-vbr
.rmx application/vnd.rn-realsystem-rmx .rnx application/vnd.rn-realplayer
.rp image/vnd.rn-realpix .rpm audio/x-pn-realaudio-plugin
.rsml application/vnd.rn-rsml .rt text/vnd.rn-realtext
.rtf application/msword .rtf application/x-rtf
.rv video/vnd.rn-realvideo .sam application/x-sam
.sat application/x-sat .sdp application/sdp
.sdw application/x-sdw .sit application/x-stuffit
.slb application/x-slb .sld application/x-sld
.slk drawing/x-slk .smi application/smil
.smil application/smil .smk application/x-smk
.snd audio/basic .sol text/plain
.sor text/plain .spc application/x-pkcs7-certificates
.spl application/futuresplash .spp text/xml
.ssm application/streamingmedia .sst application/vnd.ms-pki.certstore
.stl application/vnd.ms-pki.stl .stm text/html
.sty application/x-sty .svg text/xml
.swf application/x-shockwave-flash .tdf application/x-tdf
.tg4 application/x-tg4 .tga application/x-tga
.tif image/tiff .tif application/x-tif
.tiff image/tiff .tld text/xml
.top drawing/x-top .torrent application/x-bittorrent
.tsd text/xml .txt text/plain
.uin application/x-icq .uls text/iuls
.vcf text/x-vcard .vda application/x-vda
.vdx application/vnd.visio .vml text/xml
.vpg application/x-vpeg005 .vsd application/vnd.visio
.vsd application/x-vsd .vss application/vnd.visio
.vst application/vnd.visio .vst application/x-vst
.vsw application/vnd.visio .vsx application/vnd.visio
.vtx application/vnd.visio .vxml text/xml
.wav audio/wav .wax audio/x-ms-wax
.wb1 application/x-wb1 .wb2 application/x-wb2
.wb3 application/x-wb3 .wbmp image/vnd.wap.wbmp
.wiz application/msword .wk3 application/x-wk3
.wk4 application/x-wk4 .wkq application/x-wkq
.wks application/x-wks .wm video/x-ms-wm
.wma audio/x-ms-wma .wmd application/x-ms-wmd
.wmf application/x-wmf .wml text/vnd.wap.wml
.wmv video/x-ms-wmv .wmx video/x-ms-wmx
.wmz application/x-ms-wmz .wp6 application/x-wp6
.wpd application/x-wpd .wpg application/x-wpg
.wpl application/vnd.ms-wpl .wq1 application/x-wq1
.wr1 application/x-wr1 .wri application/x-wri
.wrk application/x-wrk .ws application/x-ws
.ws2 application/x-ws .wsc text/scriptlet
.wsdl text/xml .wvx video/x-ms-wvx
.xdp application/vnd.adobe.xdp .xdr text/xml
.xfd application/vnd.adobe.xfd .xfdf application/vnd.adobe.xfdf
.xhtml text/html .xls application/vnd.ms-excel
.xls application/x-xls .xlw application/x-xlw
.xml text/xml .xpl audio/scpls
.xq text/xml .xql text/xml
.xquery text/xml .xsd text/xml
.xsl text/xml .xslt text/xml
.xwd application/x-xwd .x_b application/x-x_b
.sis application/vnd.symbian.install .sisx application/vnd.symbian.install
.x_t application/x-x_t .ipa application/vnd.iphone
.apk application/vnd.android.package-archive .xap application/x-silverlight-app

2.3 第三方模块

art-template

vue

必须经过npm 安装

2.4 模块化概念

  • 文件做用域

  • 通讯规则

    • 加载 require
    • 导出

2.5 CommonJs模块规范

  • 模块做用域

  • 使用require来加载模块

    语法:var|let 变量名=require(‘模块’)

    做用:执行被加载模块中的代码;获得被加载模块中的exports导出接口对象

  • 使用exports接口对象来导出模块中的成员

    node是模块做用域,全部成员再当前模块有效;

    module.exports=‘字符串’

    module.exports=function(){}

    后面会覆盖前面的值;

    注意:exports是module.exports的一个引用,不能直接赋值。

2.6 require 加载规则

  • 优先从缓存加载
  • 判断模块标识
    • 核心模块
    • 第三方模块
    • 自定义模块
//路径形式的模块// ./// ..///    /xxx   通常不用//   /   标识当前模块系统所属的磁盘根路径//  .js  后缀名能够省略//  require(./foo.js)//核心模块实际上也是文件,核心模块文件已经编译到node.exe了//github.com-->node查看源码能够看到fs.js  os.js//https://github.com/nodejs/node//https://github.com/nodejs/node/tree/master/lib//第三方模块:本质上也是文件,须要经过npm下载,使用的时候仍然经过require('包名')来加载使用//不可能由任何一个第三方模块和核心模块文件名一致//既不是核心模块,也不是核心路径的模块,先找到node-modules目录,其次找其中的art-template//  node_modules/art-template//  node_modules/art-template/package.json文件//  node_modules/art-template/package.json中的main属性//  main属性中记录了art-template的入口模块,加载第三方包(包名),实际最终加载的仍是文件//  模拟实现// let template=require('art-template')// 模拟一下require('a')123456789101112131415161718192021222324252627

测试第三方模块,在node_modules下新建一个a目录,建立package.json的文件

{
  "main":"foo.js"}123

foo.js

console.log('a中的foo.js被加载了...')module.exports=()=>{
    console.log('fooooooo....')}12345
//若是package.json不存在或者main指定的入口模块也没有,则node会自动查找该目录下的index.js//即index.js会做为一个默认备选项。若是上述条件不成立,则去上级目录去寻找node_modules的目录,没有继续往//上级寻找,在a目录下建立index.jsconsole.log('a--->index')1234

若是继续往上一级查找node_modules,尚未找到,则显示:

Error: Cannot find module ‘vue’

注意:咱们的一个项目有且只有一个node_modules,这样项目均可以加载到第三方模块包,不会出现多个。

三.模板引擎

3.1 Apache功能

apache软件默认有一个www目录,此目录下的html文件均可以经过node。案例模拟实现apache项目在浏览器的效果。

读取node下的www目录文件的代码

let http=require('http')let fs=require('fs')//2.开始设置服务;let server=http.createServer()server.on('request',(req,resp)=>{
    let url=req.url    //若是是这个方式的话,去某个地方
    /*
    *   /   index.html
    *   /a.txt +/a.txt
    *  /mi/login.html
    *  /img/bg.jpg   wwwdir+/img/bg.jpg
    * */
    let wwwDir='D:/aaa/node/www'
    let filePath='/index.html'
    if(url!=='/'){
        filePath=url    }
    console.log(wwwDir+filePath)
    fs.readFile(wwwDir+filePath,(err,data)=>{
        if(err){
            console.log('404 Not Found!')
        }
        resp.end(data)
    })})//3.绑定机制;server.listen(3000,()=>{
    console.log('启动了...')})1234567891011121314151617181920212223242526272829303132

3.2 art-template

模板引擎不关心内容,只关心本身能认识的模板标记语法。Mustache是一个logic-less(轻逻辑)模板解析引擎,

它是为了使用户界面与业务数据(内容)分离而产生的,

它能够生成特定格式的文档,一般是标准的HTML文档。

好比小程序的wxml中的代码

{{userInfo.nickName}},这里的{{ }}就是Mustache的语法。1

1 介绍:

art-template 是一个简约、超快的模板引擎。
它采用做用域预声明的技术来优化模板渲染速度,从而得到接近 JavaScript 极限的运行性能,而且同时支持 NodeJS 和浏览器。

1.1 模板语法:

art-template 同时支持两种模板语法。标准语法可让模板更容易读写;原始语法具备强大的逻辑处理能力。

{{if user}}<h2>{{user.name}}</h2>{{/if}}123
<% if (user) { %><h2><%= user.name %></h2><% } %>123

使用步骤:

1.安装

npm install art-template

2.在须要使用的文件中加载art-template

let temp=require(‘art-template’)

3.查文档,使用art-template的API

在node-modules下的模板文件

<!DOCTYPE html><html style="height: 100%"><head>
 <meta charset="utf-8">
 <!--<title>{{ title }}</title>-->
 <title><%=title%></title></head><body>
   <script src="../node_modules/art-template/lib/template-web.js"></script>
   <script type="text/template" id="tp1">
      hello{{name}}
     年龄:{{age}}
    地址:{{address}}
    爱好:{{each hobbies}}{{$value}}{{/each}}
   </script><!--测试-->
 <script>
    var ret=template('tp1',{name:'jack ma',
     age:22,
     address:'河南省郑州市',
     hobbies:['吃好饭','唱好歌','开好车']
    })
   console.log(ret)
 </script></body></html>123456789101112131415161718192021222324252627

node.js使用art-template

let template=require('art-template')//template('script标签id',{对象})let result=template.render('Hello:{{name}}',{name:'张晨光'})console.log(result)12345678

结合模板来使用

let template=require('art-template')let tempstr=`<!DOCTYPE html>
<html style="height: 100%">
<head>
 <meta charset="utf-8">
 <title><%=title%></title>
</head>
<body>
     hello{{name}}
     年龄:{{age}}
    地址:{{address}}
    爱好:{{each hobbies}}{{$value}}{{/each}}
</body>
</html>`//template('script标签id',{对象})let result=template.render(tempstr,{name:'jack ma',
    age:22,
    address:'河南省郑州市',
    hobbies:['吃好饭','唱好歌','开好车']})console.log(result)123456789101112131415161718192021222324

不能使用这种方式,须要使用文件来读写

模板页面:

<!DOCTYPE html><html style="height: 100%"><head>
 <meta charset="utf-8">
 <title><%=title%></title></head><body>   
    hello{{name}}
    年龄:{{age}}
    地址:{{address}}
    爱好:{{each hobbies}}{{$value}}{{/each}}   
</body></html><!--测试-->
 <script>
    var ret=template('tp1',{name:'jack ma',
     age:22,
     address:'河南省郑州市',
     hobbies:['吃好饭','唱好歌','开好车']
    })
   console.log(ret)
 </script>12345678910111213141516171819202122

node.js代码;

let template=require('art-template')let fs=require('fs')fs.readFile('./template.html',(err,data)=>{
    if(err){
       return console.log('读取文件有误...')
    }
    //没有问题,则这样;
    //template('script标签id',{对象})
    let result=template.render(data.toString(),{name:'jack ma',
        age:22,
        address:'河南省郑州市',
        hobbies:['吃好饭','唱好歌','开好车']
    })

    console.log(result)})
相关文章
相关标签/搜索