Simple static HTML server in Node

2019-09-05 07:50发布

I want to make a simple server so I can serve local html and JS files while developing.

I tried to get a node app to just take whatever is in the URL, and respond with the page, but no luck (here's my attempt with express).

var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");

var app = express();
app.use(app.router); //use both root and other routes below
app.use(express.static('c:\\users\\pete\\projects\\')); //use static files in ROOT/public folder

app.get("/*", function(req, res){ //root dir
  fs.readFile(req.path, function(err,html){
    if(err){
        console.log(err);
        return;
    }
    res.write(html);
    res.end();
  });
});

app.listen(port, host);

but this always looks for the file at c:\, not the correct path.

I've also tried http-server for a simple static server, but it is always crashing when serving js files. https://github.com/nodeapps/http-server

I need to be able to serve your basic html,css,js files simply, and hopefully from any path provide in the URL. This is just for local front-end development. Any help?

2条回答
唯我独甜
2楼-- · 2019-09-05 08:48

If you are intrested in ultra-light http server without any prerequisites you should have a look at: mongoose you can server your files with and it's less than 10MB

查看更多
一夜七次
3楼-- · 2019-09-05 08:52

You should give complete path for fs.readFile

fs.readFile('c:\\users\\pete\\projects\\'+req.path, function(err,html){

or you can just do

var host = "127.0.0.1";
var port = 1337;
var express = require("express");

var app = express();
app.use('/', express.static('c:\\users\\pete\\projects\\'));
app.listen(port, host);
查看更多
登录 后发表回答