2

actally i'm trying to serve a html file in the browser using node js and express. unfortunatly i can't get the correct appearence of the html file.

here is the code :

var http = require('http');
var fs = require('fs');
// Chargement du fichier index.html affiché au client

var server = http.createServer(function(req, res) {
    fs.readFile('./table.html', 'utf-8', function(error, content) {

        res.writeHead(200, {"Content-Type": "text/html"});
        res.end(content);
    });
});
5
  • res.end(content); should be res.send(content); isn't it? well i don't see any expressjs code here. Commented Mar 22, 2016 at 8:53
  • You didn't run the server using server.listen(PORT);. Commented Mar 22, 2016 at 9:13
  • Like this is repost from this question stackoverflow.com/questions/20345936/… Commented Mar 22, 2016 at 9:19
  • i did run the server using server.listen(PORT); Commented Mar 22, 2016 at 9:47
  • @Jai the expresse code is in the end of the app.js . it is there i just posted the creation of the server and the call of the file. Commented Mar 22, 2016 at 9:48

2 Answers 2

2

To send a single file for a specific route use the res.sendFile() function.

var express = require('express');
var app = express();

var path = require('path');

app.get('/', function(req, res) {
    res.sendFile(path.resolve('path/to/my/file.html'));
});

app.listen(3000);

In case you want to serve all files in a directory use the express.static() middleware

var express = require('express');
var app = express();

app.use(express.static('path/to/my/directory'));

app.listen(3000);
Sign up to request clarification or add additional context in comments.

Comments

1

With express u can do something like

//init the app to extend express
var express=require("express");
var app=express();
//inside the http callback
var server = http.createServer(function(req, res) {
   app.use(express.static("./file"));
})
server.listen(8000);

3 Comments

where does your file live?...You must have your static files in a directory and serve them using express static
my file is in the /views. i changed the path of serving the file to "/views/table.html" and it is not working
No it should be express.static("views/table.html").....given that views is in the same path where ur server.js is in

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.