Discuss / JavaScript / 课外作业 (最简单的逻辑)

课外作业 (最简单的逻辑)

Topic source

嗯?

#1 Created at ... [Delete] [Delete and Lock User]

偷懒的办法: 如果fullpath == '/' 则fullpath = '/index.html',

这种情况只能单纯默认index.html 

看老师的意思 需要去获取一下当前目录下的文件列表 看看是否包含index / default 所以代码如下 (不要递归,简单问题复杂化)

这里用到一个 readdirSync 属于课外知识了 稍微度娘一下就有, 这种应属于是最简单的实现方式

var http = require("http");
var fs = require('fs'), url = require('url'), path = require('path'), process = require('process');var root = path.resolve()
// console.log('root:', root)
var server = http.createServer(function(request, response) {
  var pathname = url.parse(request.url).pathname
  console.log('pathname:', pathname)
  var fullpath = path.join(root, pathname)
  console.log('fullpath:', fullpath)
  fs.stat(fullpath, function (err, data) {
    if (err) {
      console.log('err:', err)
      response.writeHead(404)
      response.end('404 not found')
    } else if (data.isDirectory()){
      // readdirSync获取文件夹下所有文件
      var fileList = fs.readdirSync(fullpath)
      console.log('directory:', fileList)
      if (fileList.includes('index.html')) {
        fullpath += 'index.html'
      } else if (fileList.includes('default.html')) {
        fullpath += 'default.html'
      }
      response.writeHead(200)
      fs.createReadStream(fullpath).pipe(response)
    } else {
      console.log('data:', data)
      response.writeHead(200)
      // 将文件流导向response
      fs.createReadStream(fullpath).pipe(response)
    }
  })
})

// // 让服务器监听8080端口:
server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');

  • 1

Reply