10 - node - to obtain documents in the foreground traversing

Thought: Front initiate acquisition = "ajax

 

1, the front file 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> get the folder </ 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 array turn
    */
    var data = JSON.parse(xhr.responseText);
    was HTMLs = '';
    
    for(var i=0;i<data.length;i++){
      htmls += data[i]+' '
    }

    document.getElementById('div').innerHTML = htmls;
    }
  }
</script>
</body>
</html>
 
________________________________________________________
 
2, the back-end file server.js
 
const http = require('http');
const fs = require('fs');

const server = http.createServer();

server.on('request', function (req, res) {

  // to give the appropriate response for each request based on file type

  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)=>{
      /**
      * When the client and server for data communication, data format into json
      */
      res.end(JSON.stringify(data))
    })
  }else{
    // automatically binary, the browser will automatically recognize
    // Note that the path before you want to add.
    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')
});


Guess you like

Origin www.cnblogs.com/500m/p/10932661.html