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

Facilitate parent directory navigation

Hello everyone! I am currently developing an express application. At the top of my express file, I added this line to serve all static files from my working directory: app.use(express.static(__dirname)); Now, I am trying to send a file that is located in ...

Embedding a compact table using HTML on the sidebar

I am facing a challenge in this HTML code where the table appears next to the spans. How can I make sure that the spans appear below the table instead? <div> <table align="right"> <tr> <td>smthg</td> ...

How can I make a single <input> element that can handle both files and urls simultaneously?

Is there a way to enable my users to import both local and remote files using just one input field? A possible solution, inspired by Stackoverflow, is to implement tabs: Another approach could be using radio buttons like this: <style> .display ...

When resetting the function, make sure to move the class to the closest sibling element

I am currently utilizing a slider that employs the .prev and .next jQuery functions to toggle the active class, indicating which slide is being displayed. Here is the code responsible for this functionality. It identifies the current sibling with the acti ...

Is it necessary to create a backup of the ".npm" and ".node-gyp" directories?

Currently in the process of creating a backup strategy for my hard drive, I am wondering if it is necessary to include backup copies of the hidden folders "~/.npm" and "~/.node-gyp"? Are these folders simply temporary storage spaces with automatically ge ...

Removing Node from WSL: A Step-by-Step Guide

After setting up nodejs with npm on WSL2, I found myself struggling to delete, upgrade, or downgrade the node version. Despite searching on StackOverflow for solutions applicable to both Windows and Linux systems, I couldn't find any relevant answers ...

What is the solution for the error stating "Unable to locate a declaration file for the module 'request-context'."?

I am currently working on three different files: index.js, index.main.js, and app.js. My goal is to use request-context to extract a variable from index.main.js and pass it to index.js. Within my app.js file, located in the server folder, I have the follo ...

No content displaying after deploying React/Node app on Replit or Heroku

Currently, I am developing an ecommerce service using React and NodeJS/Express. While I have successfully deployed my project on Replit, I am facing an issue where it only works on my local server. On other devices, the screen remains blank. I suspect that ...

Error: Property 'onclick' cannot be set on a null object

JavaScript isn't my strong suit, so I'm struggling to solve this issue. The console is showing me the following error message: Uncaught TypeError: Cannot set property 'onclick' of null <script> var modal = document.getE ...

Is there a downside to concealing a checkbox off-screen using position: absolute for a clever workaround?

I recently came across a clever trick known as the checkbox hack, which involves hiding checkboxes on web pages by positioning them off-screen. The example provided on CSS Tricks demonstrates this technique with the following code: position: absolute; top ...

Merge the JSON data with the Node.js/Express.js response

Whenever I input somedomain.com/some_api_url?_var1=1 in a browser, the response that I receive is {"1":"descriptive string"}. In this JSON response, the index 1 can vary from 1 to n, and the "descriptive string" summarizes what the index represents. I am ...

"Border-radius becomes less prominent on pointer interaction in Chrome and Safari due to WebKit's behavior

Having an issue with a list inside a div. The problem arises when there is a div containing a list, which limits the visibility of items for users. If the limit is exceeded, a scroll bar appears inside the div to allow users to see more items. Additionally ...

Two sidebar panels displayed in the same tab on the Navbar page

In the Shiny navbarpage, is it possible to add 2 sidebar panels with space in between, as illustrated in the diagram linked below? Can we use HTML tags to achieve this spacing? https://i.sstatic.net/jXBXo.png Below is the code for it (Essentially, I requ ...

Use jQuery to switch the class of the designated DIV in the showcasing slider

Check out this jQuery slider example where I have two Divs - DIV ONE and DIV TWO. Can you help me figure out how to: 1) Automatically change the class of DIV ONE from "test" to "testc" when Slide 1 is displayed by the slider. 2) Automatically update DIV ...

Is NoSQL supported by the MySQL Community Edition?

I have decided to dive into learning and developing a Node.js application with SQL. I am aware that the MySQL Enterprise Edition offers support for NoSQL, but I'm curious if the community edition also supports NoSQL or if I need to invest in the enter ...

What could be the reason for mongoose.find producing an empty Array?

I've set up an express server and I'm having trouble retrieving tracks from my database. Even though I've created the model to match the attributes in my database, it's still returning an empty array. Any assistance would be greatly app ...

The React application functions smoothly when executed using react-scripts start, but encounters an "Unexpected SyntaxError: Unexpected Token: <" error upon building

My goal is to deploy my portfolio site using an express server and react-scripts build. Everything works perfectly fine when I run react-scripts start. However, when I try to serve up the build index.js, I encounter the following errors: 2.8b4a0c83.chunk.j ...

Utilizing jQuery to Calculate Tab Scores

Last week, my teacher and I collaborated on a fun game called rEAndom game (). The game is created using javascript, jQuery, and HTML5. One interesting feature of the game is that when you press the TAB key, a div displaying the score appears. You can chec ...

Adding a class to a field tag in a Django form: A step-by-step guide

Is there a way to add a bootstrap class to the label of an input field in a form? I know how to add classes to the input field itself, but I haven't been able to find a guide on adding a class to the label within the form declaration. Can anyone provi ...

Display information from Node.js on an HTML page

I am working on a nodejs project where I need to login on one page and display the result on another page using expressjs. Below is my code for login.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <body> <form method="PO ...