一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

 

一、静态资源服务器命令行工具

#!/usr/bin/env node

// npm i yargs
const yargs = require('yargs')
const Server = require('../src/app')
const argv = yargs
  .option('d', {
    alias: 'root',
    demand: 'false',
    type: 'string',
    default: process.cwd(),
    description: '静态文件根目录'
  })
  .option('o', {
    alias: 'host',
    demand: 'false',
    default: 'localhost',
    type: 'number',
    description: '请配置监听的主机'
  })
  .option('p', {
    alias: 'port',
    demand: 'false',
    type: 'number',
    default: 8080,
    description: '请配置端口号'
  })
  .usage('ll-server [options]')
  .example('ll-server -d / -p 9090 -o localhost', '在本机的9090端口上监听客户端的请求')
  .help('h')
  .argv
console.log(argv)
const server = new Server(argv)
server.start()

/*
1、第一行固定代码:#!/usr/bin/env node
2、package.json添加
{
  "bin": {
    "ll-server": "bin/www.js"
  }
}
3、执行命令:npm link
*/
const config = require('./config')
const http = require('http')
// npm i chalk
const chalk = require('chalk')
const path = require('path')
const url = require('url')
const fs = require('fs')
const {promisify, inspect} = require('util');
const stat = promisify(fs.stat);
const readdir = promisify(fs.readdir);
// npm i mime
const mime = require('mime')
// PowerShell:$env:DEBUG='static:*';node app.js
// process.env.DEBUG = 'static:*'
// npm i debug
const debug = require('debug')('static:app')

class Server {
  constructor(argv) {
    this.config = Object.assign({}, argv, config)
  }

  start() {
    const server = http.createServer()
    server.on('request', this.request.bind(this))
    server.listen(this.config.port, () => {
      const url = `${this.config.host}:${this.config.port}`
      debug(`server started at ${chalk.green(url)}`)
    })
  }

  async request(req, res) {
    const {pathname} = url.parse(req.url)
    const filepath = path.join(this.config.root, pathname);
    try {
      const statObj = await stat(filepath)
      if (statObj.isDirectory()) {
        const files = await readdir(filepath)
        res.setHeader('Content-Type', 'application/json')
        res.end(JSON.stringify(files.map(file => ({
          name: file,
          url: path.join(pathname, file)
        }))))
      } else {
        this.sendFile(req, res, filepath, statObj)
      }
    } catch (e) {
      debug(inspect(e))
      this.sendError(req, res)
    }
  }

  sendFile(req, res, filepath, statObj) {
    res.setHeader('Content-Type', mime.getType(filepath))
    fs.createReadStream(filepath).pipe(res)
  }

  sendError(req, res) {
    res.statusCode = 500
    res.end(`there is something wrong in the server! please try later!`)
  }
}

module.exports = Server
const debug = require('debug')('static:config')
const path = require('path')
const config = {
  host: 'localhost',
  port: 8080,
  root: path.resolve(__dirname, '..', 'public')
}
debug(config)
module.exports = config
posted on 2024-06-04 10:49  一路繁花似锦绣前程  阅读(16)  评论(0编辑  收藏  举报