Use node to achieve a simple function apache

Use node to achieve a simple function apache

1. To achieve the specified files by file name (path) access

1. The idea of ​​the words: created in the specified file inside

  	例如:我在c:/inetpub/www/ 里面创建了如下三个文件

Here Insert Picture Description
Expects an input at the client to access the file name example: http: //127.0.0.1: 3000 / index.html will locate the corresponding file, if there is no corresponding file is returned 404

const http = require('http');
const fs = require('fs');
const server = http.createServer();

//定义成全局的方便修改
const BASE = 'c:/inetpub/www';

server.on('request',(req,res)=>{
    console.log('客户端已连接',req.url);
    const url = req.url;
    let filePath = '/index.html';
    if(url !== '/'){
        filePath = url;
    }
    //读对应文件
    fs.readFile(BASE+filePath,(err,data)=>{
        if(err){
          return  res.end('404 Not Found');
        }
        //指定文件在网页上显示的格式,例如有中文需要指定utf-8,图片需要把image/jpeg,网页的是text/html,其他格式的文件也有对应的格式
        res.setHeader('Content-Type','text/plain; charset=utf-8')
        res.end(data);
    })

})

server.listen(5000,()=>{
    console.log('服务器已开启请访问:http://127.0.0.1:3000')
})

2. To achieve the effect of directory

Www directory when read in this document is not index.html is the emergence of a directory, as follows:
Here Insert Picture Description
you want to achieve this effect it needs to be rendered on the server side of this page, directory data can be

const fs = require('fs');
fs.readDir(path,(err,data) => {
	console.log(data) //[...]
})

String may then be spliced ​​using a String.replace () method render the page, of course, also be used to render template engine, exemplified here using art-template

npm install art-template --save

Loading the package, and then written in the corresponding page format

<html>
<head>
	<title></title>
</head>
<body>
	{{each files}}
		...str...{{$value}}...
	{{/each}}
</body>
</html>

In the last set js file click on the ok

Published 84 original articles · won praise 204 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_44983621/article/details/104333795