node.js读取字体图标时出错解决 NodeJs笔记

261 阅读1分钟

字体图标通过 icomoon 网站下载:

6.jpg

后台代码如下:

const http = require("http");
const fs = require("fs");

const server = http.createServer(function(request,response) {

    let filePath = "static" + request.url;

    fs.readFile(filePath,(err,data) => {
        if(err) {
            response.statusCode = 500;
            console.log("error:" + filePath);  //打印错误路径
            console.log(err);  // 打印错误
            response.end("文件读取失败...");
            return;
        }
        response.end(data);
    });
}).listen(9000,function() {
    console.log("start...");
});

访问网页时出现字体图标无法显示问题:

4.jpg

控制台报错:

5.jpg

css文件中对字体图标的调用,但是通过本地文件访问html文件可正常显示:

@font-face {
    font-family: 'icomoon';
    src:  url('../resourcefonts/icomoon.eot?gx58j3');
    src:  url('../resourcefonts/icomoon.eot?gx58j3#iefix') format('embedded-opentype'),
    url('../resourcefonts/icomoon.ttf?gx58j3') format('truetype'),
    url('../resourcefonts/icomoon.woff?gx58j3') format('woff'),
    url('../resourcefonts/icomoon.svg?gx58j3#icomoon') format('svg');
    font-weight: normal;
    font-style: normal;
    font-display: block;
}

解决方案

修改css文件中的对字体图标路径的引用:

7.jpg

修改后:

@font-face {
    font-family: 'icomoon';
    src:  url('../resourcefonts/icomoon.eot?gx58j3');
    src:  url('../resourcefonts/icomoon.eot?gx58j3#iefix') format('embedded-opentype'),
    url('../resourcefonts/icomoon.ttf') format('truetype'),
    url('../resourcefonts/icomoon.woff') format('woff'),
    url('../resourcefonts/icomoon.svg?gx58j3#icomoon') format('svg');
    font-weight: normal;
    font-style: normal;
    font-display: block;
}

效果展示:

8.jpg


报错原因及其他问题

1、原因未知,猜测可能是无法读取?后面的内容,索性删除后续字符串,最终解决了问题,删除字符串后,依然不影响本地html文件的图标显示

2、如若出现字体图标无法正常显示的其他问题,可参考(转载,该文章讨论了关于字体图标无法正常显示的问题,可能会有帮助):stackoverflow.com/questions/3…