Node.js 极简笔记

Node.js

一.Node基础

概念: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.js

1.编写js文件

2.定位到目录

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

let str="hello world"

console.log(str)
console.log(window)  //没有bom
console.log(document) //没有dom

多出来的功能:

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

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

关于参数的代码理解

//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());
})

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/来访问...')
})
//1.导入http包
let http=require('http')
//2.定义server变量,返回一个server实例;
let server=http.createServer()
//3.服务器的响应,接受request请求,产生会回调事件
//增加参数:request、response
server.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/来访问...')
})

根据不同的url返回不同的服务

let url=request.url

url返回的是/之后的路径

//1.导入http包
let http=require('http')
//2.定义server变量,返回一个server实例;
let server=http.createServer()
//3.服务器的响应,接受request请求,产生会回调事件
//增加参数:request、response
server.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/来访问...')
})

二.模块

模块分为三种:

  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');
    }

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);
//});

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('是一个目录');
    }
});

2.2 自定义模块

详细介绍自定义模块:

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

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

在另外一个文件进行调用

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

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'))
//输出端口号;
console.log('请求端口号:'+request.socket.remotePort)
console.log('请求地址:'+request.socket.remoteAddress)

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('服务器启动可以访问了...')
})

可以启动多个服务,端口号不同就行!!!

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('服务器启动可以访问了...')
})

可以读取图片的程序升级

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('服务器启动可以访问了...')
})

Http Mime Type

文件扩展名Content-Type(Mime-Type)文件扩展名Content-Type(Mime-Type)
.*( 二进制流,不知道下载文件类型)application/octet-stream.tifimage/tiff
.001application/x-001.301application/x-301
.323text/h323.906application/x-906
.907drawing/907.a11application/x-a11
.acpaudio/x-mei-aac.aiapplication/postscript
.aifaudio/aiff.aifcaudio/aiff
.aiffaudio/aiff.anvapplication/x-anv
.asatext/asa.asfvideo/x-ms-asf
.asptext/asp.asxvideo/x-ms-asf
.auaudio/basic.avivideo/avi
.awfapplication/vnd.adobe.workflow.biztext/xml
.bmpapplication/x-bmp.botapplication/x-bot
.c4tapplication/x-c4t.c90application/x-c90
.calapplication/x-cals.catapplication/vnd.ms-pki.seccat
.cdfapplication/x-netcdf.cdrapplication/x-cdr
.celapplication/x-cel.cerapplication/x-x509-ca-cert
.cg4application/x-g4.cgmapplication/x-cgm
.citapplication/x-cit.classjava/*
.cmltext/xml.cmpapplication/x-cmp
.cmxapplication/x-cmx.cotapplication/x-cot
.crlapplication/pkix-crl.crtapplication/x-x509-ca-cert
.csiapplication/x-csi.csstext/css
.cutapplication/x-cut.dbfapplication/x-dbf
.dbmapplication/x-dbm.dbxapplication/x-dbx
.dcdtext/xml.dcxapplication/x-dcx
.derapplication/x-x509-ca-cert.dgnapplication/x-dgn
.dibapplication/x-dib.dllapplication/x-msdownload
.docapplication/msword.dotapplication/msword
.drwapplication/x-drw.dtdtext/xml
.dwfModel/vnd.dwf.dwfapplication/x-dwf
.dwgapplication/x-dwg.dxbapplication/x-dxb
.dxfapplication/x-dxf.ednapplication/vnd.adobe.edn
.emfapplication/x-emf.emlmessage/rfc822
.enttext/xml.epiapplication/x-epi
.epsapplication/x-ps.epsapplication/postscript
.etdapplication/x-ebx.exeapplication/x-msdownload
.faximage/fax.fdfapplication/vnd.fdf
.fifapplication/fractals.fotext/xml
.frmapplication/x-frm.g4application/x-g4
.gbrapplication/x-gbr.application/x-
.gifimage/gif.gl2application/x-gl2
.gp4application/x-gp4.hglapplication/x-hgl
.hmrapplication/x-hmr.hpgapplication/x-hpgl
.hplapplication/x-hpl.hqxapplication/mac-binhex40
.hrfapplication/x-hrf.htaapplication/hta
.htctext/x-component.htmtext/html
.htmltext/html.htttext/webviewhtml
.htxtext/html.icbapplication/x-icb
.icoimage/x-icon.icoapplication/x-ico
.iffapplication/x-iff.ig4application/x-g4
.igsapplication/x-igs.iiiapplication/x-iphone
.imgapplication/x-img.insapplication/x-internet-signup
.ispapplication/x-internet-signup.IVFvideo/x-ivf
.javajava/*.jfifimage/jpeg
.jpeimage/jpeg.jpeapplication/x-jpe
.jpegimage/jpeg.jpgimage/jpeg
.jpgapplication/x-jpg.jsapplication/x-javascript
.jsptext/html.la1audio/x-liquid-file
.larapplication/x-laplayer-reg.latexapplication/x-latex
.lavsaudio/x-liquid-secure.lbmapplication/x-lbm
.lmsffaudio/x-la-lms.lsapplication/x-javascript
.ltrapplication/x-ltr.m1vvideo/x-mpeg
.m2vvideo/x-mpeg.m3uaudio/mpegurl
.m4evideo/mpeg4.macapplication/x-mac
.manapplication/x-troff-man.mathtext/xml
.mdbapplication/msaccess.mdbapplication/x-mdb
.mfpapplication/x-shockwave-flash.mhtmessage/rfc822
.mhtmlmessage/rfc822.miapplication/x-mi
.midaudio/mid.midiaudio/mid
.milapplication/x-mil.mmltext/xml
.mndaudio/x-musicnet-download.mnsaudio/x-musicnet-stream
.mochaapplication/x-javascript.movievideo/x-sgi-movie
.mp1audio/mp1.mp2audio/mp2
.mp2vvideo/mpeg.mp3audio/mp3
.mp4video/mpeg4.mpavideo/x-mpg
.mpdapplication/vnd.ms-project.mpevideo/x-mpeg
.mpegvideo/mpg.mpgvideo/mpg
.mpgaaudio/rn-mpeg.mppapplication/vnd.ms-project
.mpsvideo/x-mpeg.mptapplication/vnd.ms-project
.mpvvideo/mpg.mpv2video/mpeg
.mpwapplication/vnd.ms-project.mpxapplication/vnd.ms-project
.mtxtext/xml.mxpapplication/x-mmxp
.netimage/pnetvue.nrfapplication/x-nrf
.nwsmessage/rfc822.odctext/x-ms-odc
.outapplication/x-out.p10application/pkcs10
.p12application/x-pkcs12.p7bapplication/x-pkcs7-certificates
.p7capplication/pkcs7-mime.p7mapplication/pkcs7-mime
.p7rapplication/x-pkcs7-certreqresp.p7sapplication/pkcs7-signature
.pc5application/x-pc5.pciapplication/x-pci
.pclapplication/x-pcl.pcxapplication/x-pcx
.pdfapplication/pdf.pdfapplication/pdf
.pdxapplication/vnd.adobe.pdx.pfxapplication/x-pkcs12
.pglapplication/x-pgl.picapplication/x-pic
.pkoapplication/vnd.ms-pki.pko.plapplication/x-perl
.plgtext/html.plsaudio/scpls
.pltapplication/x-plt.pngimage/png
.pngapplication/x-png.potapplication/vnd.ms-powerpoint
.ppaapplication/vnd.ms-powerpoint.ppmapplication/x-ppm
.ppsapplication/vnd.ms-powerpoint.pptapplication/vnd.ms-powerpoint
.pptapplication/x-ppt.prapplication/x-pr
.prfapplication/pics-rules.prnapplication/x-prn
.prtapplication/x-prt.psapplication/x-ps
.psapplication/postscript.ptnapplication/x-ptn
.pwzapplication/vnd.ms-powerpoint.r3ttext/vnd.rn-realtext3d
.raaudio/vnd.rn-realaudio.ramaudio/x-pn-realaudio
.rasapplication/x-ras.ratapplication/rat-file
.rdftext/xml.recapplication/vnd.rn-recording
.redapplication/x-red.rgbapplication/x-rgb
.rjsapplication/vnd.rn-realsystem-rjs.rjtapplication/vnd.rn-realsystem-rjt
.rlcapplication/x-rlc.rleapplication/x-rle
.rmapplication/vnd.rn-realmedia.rmfapplication/vnd.adobe.rmf
.rmiaudio/mid.rmjapplication/vnd.rn-realsystem-rmj
.rmmaudio/x-pn-realaudio.rmpapplication/vnd.rn-rn_music_package
.rmsapplication/vnd.rn-realmedia-secure.rmvbapplication/vnd.rn-realmedia-vbr
.rmxapplication/vnd.rn-realsystem-rmx.rnxapplication/vnd.rn-realplayer
.rpimage/vnd.rn-realpix.rpmaudio/x-pn-realaudio-plugin
.rsmlapplication/vnd.rn-rsml.rttext/vnd.rn-realtext
.rtfapplication/msword.rtfapplication/x-rtf
.rvvideo/vnd.rn-realvideo.samapplication/x-sam
.satapplication/x-sat.sdpapplication/sdp
.sdwapplication/x-sdw.sitapplication/x-stuffit
.slbapplication/x-slb.sldapplication/x-sld
.slkdrawing/x-slk.smiapplication/smil
.smilapplication/smil.smkapplication/x-smk
.sndaudio/basic.soltext/plain
.sortext/plain.spcapplication/x-pkcs7-certificates
.splapplication/futuresplash.spptext/xml
.ssmapplication/streamingmedia.sstapplication/vnd.ms-pki.certstore
.stlapplication/vnd.ms-pki.stl.stmtext/html
.styapplication/x-sty.svgtext/xml
.swfapplication/x-shockwave-flash.tdfapplication/x-tdf
.tg4application/x-tg4.tgaapplication/x-tga
.tifimage/tiff.tifapplication/x-tif
.tiffimage/tiff.tldtext/xml
.topdrawing/x-top.torrentapplication/x-bittorrent
.tsdtext/xml.txttext/plain
.uinapplication/x-icq.ulstext/iuls
.vcftext/x-vcard.vdaapplication/x-vda
.vdxapplication/vnd.visio.vmltext/xml
.vpgapplication/x-vpeg005.vsdapplication/vnd.visio
.vsdapplication/x-vsd.vssapplication/vnd.visio
.vstapplication/vnd.visio.vstapplication/x-vst
.vswapplication/vnd.visio.vsxapplication/vnd.visio
.vtxapplication/vnd.visio.vxmltext/xml
.wavaudio/wav.waxaudio/x-ms-wax
.wb1application/x-wb1.wb2application/x-wb2
.wb3application/x-wb3.wbmpimage/vnd.wap.wbmp
.wizapplication/msword.wk3application/x-wk3
.wk4application/x-wk4.wkqapplication/x-wkq
.wksapplication/x-wks.wmvideo/x-ms-wm
.wmaaudio/x-ms-wma.wmdapplication/x-ms-wmd
.wmfapplication/x-wmf.wmltext/vnd.wap.wml
.wmvvideo/x-ms-wmv.wmxvideo/x-ms-wmx
.wmzapplication/x-ms-wmz.wp6application/x-wp6
.wpdapplication/x-wpd.wpgapplication/x-wpg
.wplapplication/vnd.ms-wpl.wq1application/x-wq1
.wr1application/x-wr1.wriapplication/x-wri
.wrkapplication/x-wrk.wsapplication/x-ws
.ws2application/x-ws.wsctext/scriptlet
.wsdltext/xml.wvxvideo/x-ms-wvx
.xdpapplication/vnd.adobe.xdp.xdrtext/xml
.xfdapplication/vnd.adobe.xfd.xfdfapplication/vnd.adobe.xfdf
.xhtmltext/html.xlsapplication/vnd.ms-excel
.xlsapplication/x-xls.xlwapplication/x-xlw
.xmltext/xml.xplaudio/scpls
.xqtext/xml.xqltext/xml
.xquerytext/xml.xsdtext/xml
.xsltext/xml.xslttext/xml
.xwdapplication/x-xwd.x_bapplication/x-x_b
.sisapplication/vnd.symbian.install.sisxapplication/vnd.symbian.install
.x_tapplication/x-x_t.ipaapplication/vnd.iphone
.apkapplication/vnd.android.package-archive.xapapplication/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')

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

{
  "main":"foo.js"
}

foo.js

console.log('a中的foo.js被加载了...')

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

如果继续往上一级查找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('启动了...')
})

3.2 art-template

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

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

它可以生成特定格式的文档,通常是标准的HTML文档。

比如小程序的wxml中的代码

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

1 介绍:

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

1.1 模板语法:

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

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

使用步骤:

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>

node.js使用art-template

let template=require('art-template')



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

console.log(result)

结合模板来使用

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)

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

模板页面:

<!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>

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)

})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

teayear

读后有收获可以获取更多资源

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值