日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Node.js 极简笔记

發布時間:2024/1/23 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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('讀取文件失敗!')elseconsole.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.urlconsole.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/來訪問...') })

二.模塊

模塊分為三種:

  • 內置模塊
  • 自定義模塊
  • 第三方模塊
  • 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.urlif(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.urlif(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)}) 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

    總結

    以上是生活随笔為你收集整理的Node.js 极简笔记的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。