思想 : 前台主动发起获取 =》 ajax
1,前台文件 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body{
background: skyblue;
padding: 50px;
}
</style>
</head>
<body>
<h1>获取文件夹</h1>
<div id="div"></div>
<script>
var xhr = new XMLHttpRequest();
xhr.open('get','/file_list');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
/*
* json 转 数组
*/
var data = JSON.parse(xhr.responseText);
var htmls = '';
for(var i=0;i<data.length;i++){
htmls += data[i]+' '
}
document.getElementById('div').innerHTML = htmls;
}
}
</script>
</body>
</html>
________________________________________________________
2,后端文件 server.js
const http = require('http');
const fs = require('fs');
const server = http.createServer();
server.on('request', function (req, res) {
// 根据每次请求的文件类型给予相应的响应
var urls = req.url;
console.log(urls);
if(urls=='/'){
res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
fs.readFile('./index.html', 'utf-8', function (err, data) {
if (err) console.log(err)
res.end(data)
});
}else if(urls == '/file_list'){
fs.readdir('./','utf8',(err,data)=>{
/**
* 客户端与服务端进行数据通信时 , 将数据转化为 json 格式
*/
res.end(JSON.stringify(data))
})
}else{
// 自动为二进制,浏览器会自动识别
// 注意路径前要加 .
fs.readFile('.'+urls, function (err, data) {
if (err) console.log(err)
res.end(data)
});
}
});
server.listen(1234, () => {
console.log('this server is runing on 1234')
});
来源:oschina
链接:https://my.oschina.net/u/4274516/blog/3522114