为什么Node.js无法提供.woff文件服务

9
我从谷歌网络字体中下载了 .woff 文件,是因为某些中国网络原因。之前我在 Github Pages 上使用了 @font-face ,它可以工作。但这次我花了一个小时才找到了问题出在哪里。
我使用 Node 来提供静态文件服务,使用了 mime,而且 content-type 显示为 application/x-font-woff。我的 CoffeeScript 代码如下:
exports.read = (url, res) ->
  filepath = path.join __dirname, '../', url
  if fs.existsSync filepath
    file_content = fs.readFileSync filepath, 'utf8'
    show (mime.lookup url)
    res.writeHead 200, 'content-type': (mime.lookup url)
    res.end file_content
  else
    res.writeHead 404
    res.end()

由于 Github Pages 上 .woffcontent-typeapplication/octet-stream,所以我注释掉了代码中的那一行以使它与之相同。但它仍然失败了:

exports.read = (url, res) ->
  filepath = path.join __dirname, '../', url
  if fs.existsSync filepath
    file_content = fs.readFileSync filepath, 'utf8'
    show (mime.lookup url)
    # res.writeHead 200, 'content-type': (mime.lookup url)
    res.end file_content
  else
    res.writeHead 404
    res.end()

最后,我将服务器切换到Nginx来提供.woff文件。最终它开始工作了。
但是,我该如何在Node上修复这个问题?

实际上,使用nginx提供文件通常是一个更好的想法。你为什么要在node.js上这样做呢? - VBart
@VBart 因为只有不到5个静态文件需要提供服务,而且这个小应用程序需要Node,所以我认为仅使用Node在部署方面可能更好。 - jiyinyiyong
1个回答

5
在这一行中,fs.readFileSync(filepath, 'utf8') 中的编码设置为 'utf8'。需要改为 'binary'
此外,res.end(file_content) 函数需要传递正确的编码。尝试使用 res.end(file_content, 'binary')
我曾经遇到过同样的问题,不得不自己解决,似乎在网上没有找到这个答案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接