electron起一個http服務

項目需要在electron中起一個http服務用於訪問本地的音頻文件,經過研究,其實和普通的http服務一樣
audioServer.js文件:

const path = require('path')
const http = require('http')
const fs = require('fs')
const os = require('os')

function audioServer(callback) {
  const server = http.createServer((req, res) => {
    const filePath = path.join(os.tmpdir(), decodeURIComponent(req.url))
    fs.stat(filePath, (err, stats) => {
      // 這個header用於支持斷點續傳
      res.setHeader('Accept-Ranges', 'bytes')
      res.setHeader('Content-Length', stats.size)
      // 返回一個流媒體
      fs.createReadStream(filePath).pipe(res)
    })
  })
  server.listen(7888, '127.0.0.1', () => {
    callback()
  })
}
export default audioServer

index.js文件:

  audioServer(() => {
    win.mainWin.loadURL(winURL)
  })
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章