Node.js的npm包管理器及ejs的使用

1,306 阅读1分钟

npm(node package manage)是Node.js附带的第三方软件包管理器,可以为Node.js提供更多的功能支持。

安装npm与ejs

安装npm

安装Node.js的时候npm就随之安装了

node -v
npm -v

安装ejs

npm install ejs

使用ejs

hello.js,模板文件

<html>
    <head><title><%= title %></title></head>
    <body>
        <%= content %>
    </body>
</html>

server.js,服务端

const http = require('http');
const fs = require('fs');
const ejs = require('ejs');

var template = fs.readFileSync(__dirname + '/hello.ejs', 'utf-8');
const server = http.createServer((req, res) => {
    var data = ejs.render(template, {
        title: 'hello.ejs',
        content: '<strong>hello ejs</strong>'
    });
    res.setHeader('Content-Type', 'text/html');
    res.statusCode = 200;
    res.end(data);
})

const hostname = '127.0.0.1';
const port = 3000;
server.listen(port, hostname, () => {
    console.log(`Server runing at http:/${hostname}:${port}/`);
});

目录结构

执行

# 01 安装ejs
npm install ejs

# 02 运行
node server.js

# 03 浏览器访问http://127.0.0.1:3000