What is the best way to serve a .ttf file in node.js with the http and fs libraries?

I am running a basic node server and I have a CSS file that is trying to load a font from the server:

@font-face{
     font-family: 'NiagaraSolid-Reg';
     src: url('http://localhost:1111/NIAGSOL.TTF');
}

This is my attempt at serving the font file. Usually, this setup works for .html, .css, and .js files:

http.createServer(function(request,response){
    var arguments=request.url.slice(1).split("/");
    switch(arguments[0]){
        case "NIAGSOL.TTF":
            response.end(fs.readFileSync("website/NIAGSOL.TTF").toString());
            break;
        //etc 
})

However, when I try this method, Chrome shows an error message:

Failed to decode downloaded font: http://localhost:1111/NIAGSOL.TTF

I have tried looking for solutions online, but everything I found was too complex for me to understand without prior knowledge of buffers, streams, binaries, encodings, etc. I need a simple explanation on how to serve a .tff file as if you were explaining it to a five-year-old.

Thank you!

Answer №1

Tips for serving images in nodejs

I stumbled upon this helpful link that provided me with a solution. Out of curiosity, I decided to experiment with

response.end(fs.readFileSync("website/NIAGSOL.TTF"),"binary");
and it surprisingly worked. The reason behind its success remains unknown but hey, it did the job!

Answer №2

When creating a raw http server in Node.js, it is important to specify the "Content-Type" header in the response. For example, if you are serving an HTML file, you should set the content type to "text/html". Similarly, when serving .ttf files, make sure to set the appropriate content type on the response. In this case, you would use "application/x-font-ttf".

http.createServer(function (req, res) {
    res.writeHead(400, { "Content-Type": "application/x-font-ttf" });
});
You will have to implement your own logic for handling different types of files that your server may serve. Just ensure that for .ttf files, you set the header as described above.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using NodeJs to Render HTML Templates and Implement Logic on the Server Side

Hello, I am currently working on developing a widget module for my Angular 1 based UI project. This widget is meant to display real-time information. My design involves sending an HTML view to the client from the Node server (potentially using Express.js) ...

What could be causing the occasional appearance of a tiny glitch, like a pixel dot, below a menu item when utilizing this hover effect?

Occasionally, a tiny dot appears almost imperceptibly, like the one below the "prices" menu item: https://i.stack.imgur.com/kyaP3.png This is the hover effect code I created: :root { box-sizing: border-box; } *, *::before, *::after { box-sizing: ...

Syntax Error in Node.js for MongoDB: Unexpected token or invalid symbol

I'm having trouble figuring out what's going on. Node v16.4.2, NPM v7.18.1 const mongoose = require("mongoose"); // const dotenv = require('dotenv') require('dotenv').config({path:'variables.env'}); mongoo ...

Creating a project that utilizes Bing Translate and the Node.js programming language

As I work on developing a web application that enables users to translate text using the Bing translator API, I am facing an issue. I attempted to execute a translator.js file via a script tag, but encountered a roadblock since Node.js code cannot be run t ...

The reason the section's height is set to 0 is due to the absolute positioning of the div

Currently, I have a section tag with three divs inside that are positioned absolute (used for the isotope plugin). <section id="section1" class="cd-section"> // pos. static/relative has height 0px <div class="itemIso"> // pos. absolute, he ...

Renew Firebase Token

Currently, my email and password authentication flow in web Firebase JavaScript involves generating a token that I then verify on my node.js backend using firebase-admin. To make things easier, I store this generated token in the browser's local/sessi ...

Is NodeJS significantly slower compared to PHP?

Currently running a small-scale web server under Apache + PHP + MySQL, I am considering the possibility of switching to NodeJS. The server's primary functions are serving static files and querying the database for select and insert operations only. I ...

Parsing of the module failed due to an unexpected character appearing when trying to insert a TTF file into the stylesheet

As a newcomer to Angular, I recently completed the tutorial and am now working on my first app. While trying to add an OTF file, everything went smoothly. However, when I made a change to my app.component.css file and included this code snippet: @font-fa ...

Updating the registry in package-lock.json using NPM

To enhance security measures, I am looking to implement a specific repository in my system. However, despite efforts, the package-lock.json file continues to reference https://registry.npmjs.org/. Are there any methods available to enforce this change? ...

Creating a Mongoose model with an array property that includes instances of the same model as the parent

My current challenge involves creating a Note object with a subnote property that should be of the same type as the parent model. Currently, I have achieved this by creating two identical models with different names and having them reference each other. He ...

The padding of elements changes accordingly as the dimensions (width/height) of the header are adjusted

Currently, I'm tackling the challenges of working on my website and trying to understand JavaScript better. I am facing an issue where I want my aside menu's padding to adjust when my header shrinks in height. Furthermore, at the end of the web ...

What causes the fixed div to appear when scrolling horizontally?

I have replicated this issue in a live example: http://jsfiddle.net/pda2yc6s When scrolling vertically, a specific div element sticks to the top. However, if the window is narrower than the wrapper's width and you scroll horizontally, the sticky elem ...

Issue with jQuery fadeTo() not working after appendTo() function completes

I am facing a problem with the code below that is meant to create a carousel effect for my website. The main issue I am encountering is that the original fadeTo() function does not actually fade the elements, but rather waits for the fade time to finish an ...

Leveraging hogan.js alongside express.js and vhosts

Struggling to integrate hogan.js with express.js properly: I attempted the following steps: var hogan = require('hogan.js') ... app.set('view engine', 'hogan'); and then added: app.register('.hogan', hogan); But ...

Following the integration of DOTENV, the server functionality in the express application generated by express generator seems to have

Once I add DOTENV to the server setup in an Express application created using the express generator, the server stops working. Here is how I'm including DOTENV in my app.js file: require('dotenv').config({ path: 'variables.env' } ...

Exploring the capability of the Videoshow NPM module in conjunction with

I've been working on using videoshow to convert a series of images into a video. I've made several changes to my code, but it seems like it's pretty much the same as what's described in the module's documentation. However, I keep e ...

Is it possible to adjust the color of a pseudo class to align with the color of a different class?

Creating a unique 'block' element on a webpage named 'test-div' has been quite the challenge. Adding an additional class to test-div changes the background color, such as: test-div test-div-bg-bright-gold test-div test-div-bg-dark-blu ...

The SVG icon displays properly when viewed on a local machine, but is missing when the website is deployed

Something strange is happening with my SVG sprites. Everything seems to be working fine when I test my code locally, but once deployed on Firebase, one of the SVG images fails to appear. What could be causing this issue? Below is the code for two SVGs: sm ...

The npm package has been successfully installed, but VS Code is having trouble locating it

Currently, I am in the process of developing a simple npm package known as type-exception using TypeScript. After successful test runs and publication on NPM, I have been able to install it into another project (project B). However, upon importing it as a ...

Ways to Adjust Website Scaling for Varying Screen Sizes

Is there a way to adjust my website's scale based on the device width, such as changing it to 0.7 for certain devices? The only information I've found so far is using the <meta> tag: <meta name="viewport" content="width=device-width, i ...