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

301
Visualizações
create a web server for local html using node

I'm tring to create a simple web server to run my local html file, and now I can get a server running on localhost using code below

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html', 'utf8');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'html'});
  res.end(index);
}).listen(3000);

But there is a problem that every time I changed my html file, the web page on localhost is still the old one, I need to restart the server to make the changes visible.

I want to improve that and I tried to use koa or express, like code below

const express = require("express");
const app = express();

app.listen(3000, () => {
  console.log("Application started and Listening on port 3000");
});

app.get("/", (req, res) => {
  res.sendFile("test.html");
});

And I found that express can serve real-time html files, I don't need to restart serve when files change.

How can I use http moudle to achieve that?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Currently you read the file when the program starts up. Then each time you get a request you serve up the data from the variable.

Move that code inside the callback function that runs when you get a request, then it will be updated each time a request comes in.

http.createServer(function (req, res) {
  var index = fs.readFileSync('index.html', 'utf8');
  res.writeHead(200, {'Content-Type': 'html'});
  res.end(index);
}).listen(3000);

You could avoid reading the file on each request by having the variable outside the function (as in your original code) and watching the file for changes (and updating the variable in response).

That said, using Express and its static module will provide benefits with caching and I'd recommend it over rolling your own.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use nodemon.

npm install -g nodemon

nodemon server.js
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