Premise: To use the module engine in express need to install the template engine that will be used in this project, of course, Express is also to be installed. In the following example, the template engine I used was pug (together called Jade)
My directory structure is as follows:
The root directory is static, the public folder under the root directory, which is the root directory of the files (slice file, CSS file, js file de). The view under the root directory is the root directory of the template file. The app.js in the root directory is the startup file,
The code is as follows:
//introducing the necessary modules//Express.static is the only built-in middleware in Express 4.0 and does not require additionalvarExpress = require (' Express ');varApp =Express ();//set the template engine to Pug, or you can set it to another, where I have installed pugApp.set (' View engine ', ' Pug ');//set the template file to store the directory, I will so the template file exists in the View folder//it means to put the template file in the same directory-level view folder as the current fileApp.set (' views ', ' view ');//use express.static as a middleware//it means to load a static file in public, which is at the same directory level as the current fileApp.use (express.static (' public '))); App.get (‘/‘,function(req,res) {//render the View folder in the Index.pug template, because the template engine has been set to Pug, so here can not add suffix nameRes.render (' Index ');}); App.listen (3000,function() {Console.log (' Reading ');});
The code for the Index.pug file is as follows
DOCTYPE htmlhtml head (lang= ' en ') title index meta (charset= ' utf-8 ') //-because in App.js will Express.static ( The first parameter is set to public, //-so will be in public to find Css/test/css, even if written. /css/test.css, and so on, is also //-in public to find css/test.css, no matter how many points before css/test.css, Req.url are css/test.css link (type= ' Text/css ', rel= ' stylesheet ', href= ' css/test.css ') Body | index script (type= ' text/javascript ', src= ' JS /index.js ')
Express 4.x template engine with express.static