Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
How do I send multiple files when the server is requested using node.js?

I'm new to anything web-development related (I've only been coding using luau for about a year now), and I'm having trouble sending multiple files when my server gets pinged, because I want to have a separate style.css file, as well as different script things.

I've left out MouseDraw.js and style.css, but when I added them directly into index.html they worked, and I can't see them when I inspect element on the website so I think it's just that they aren't being sent.

Is it possible to send them or do I have to just put them in every file?

I would post an image of how it's structured but I'm new so I can't, but it's all under a folder, and then there's just 'Server.js' and a folder called Client, which has everything I want to send to the client.

Server code:

const http = require('http');

const fs = require('fs').promises

const hostname = 'localhost';
const port = 8000;

let loadedPageInfo;

fs.readFile(__dirname + "/Client/index.html")  // Get and read the HTML data for this page
    .then((contents) => {
        loadedPageInfo = contents
    })
    .catch((error) => {
        console.log(`Could not load index.html ${error}`)
    })

const server = http.createServer((req, res) => {
    res.end(loadedPageInfo || "Error loading");
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

Client:

index.html:


<head>
    <title>Drawing</title>
    <link rel = "stylsheet" type = "text/css" href = "style.css">

</head>

<body> 
    <h1>Heading One</h1>
    <p1>Message from my computer:</p1>

    <p2><samp><br><br>File not found.<br>Press F1 to do nothing</samp></p2>

</body>

<script> src = "MouseDraw.js" </script>

</html>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

style.css will be requested as a new http request from the browser. It will be asking for /style.css. Your http server just sends loadedPageInfo no matter what the incoming request path is, so when the browser asks for /style.css, your http server just sends it loadedPageInfo. The browser will probably see that it's an incorrect file type (e.g. not a CSS file) and will end up ignoring it.

Same thing would happen for MouseDraw.js. If you want the browser to be able to get /style.css and /MouseDraw.js, then you will need to check for those in your http server and send the right file that matches the request.

In the Express framework, you can configure express.static() to automatically serve a bunch of static HTML files like these, but without that, you have to literally write code for each separate http request that you want to serve, checking the incoming path of the request and sending the file that matches that request.

I'd really recommend using the very lightweight Express web server framework as it makes all of this simpler without getting in your way. But here's the general idea for coding it manually:

function sendFile(res, file) {
    const filename = path.join(__dirname, "/Client", file);
    fs.readFile(filename).then(data => {
        res.end(data);
    }).catch(err => {
        console.log(err);
        res.statusCode = 404;
        res.end();
    });
}

const server = http.createServer((req, res) => {
    switch(req.url) {
        case "/":
            sendFile(res, "index.html");
            break;
        case "/style.css":
            sendFile(res, "style.css");
            break;
        case "/MouseDraw.js":
            sendFile(res, "MouseDraw.js");
            break;
        default:
            res.statusCode = 404;
            res.end();
            break;
    }
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda