node.js发送html页面,Node.js提供HTML页面和静态内容

不,您不必以编程方式列出所有静态文件。您可以通过将middleware绑定到服务器的根目录来动态地为它们提供服务。

这是我已经完成的一个小express.js脚本,它基本上是一个非常简单的Web服务器,可以提供任何东西和漂亮的HTML。

// This servers a file..

var serveFile = function(filePath, res){

var options = {

dotfiles: 'deny',

headers: {

'x-timestamp': Date.now(),

'x-sent': true

}

};

res.sendFile(filePath, options, function (err) {

if (err) {

console.log(err);

res.status(err.status).end();

}

});

};

// Serve web files

app.use("/", function (req, res, next) {

var filePath = (absoluteServePath + req.originalUrl).replace(/\//g,"\\");

var checkFilePath = function(filePath){

return new Promise(function(resolve, reject) {

fs.access(filePath, fs.F_OK, function(err) {

if(!err){

// If FILE / DIR exists check if file or DIR

if(fs.lstatSync(filePath).isDirectory() == true){

reject();

}

else{

resolve();

}

}else{

reject(err);

}

});

});

};

checkFilePath(filePath).then(function(){

serveFile(filePath,res);

},function(){

// Check if path ends with a slash

var endsWithSlash = filePath.substr(filePath.length - 1) == "\\";

// Check if a index.html exists in the path

var indexHTMLPath = filePath + ((endsWithSlash == true) ? "" : "\\") + "index.html";

checkFilePath(indexHTMLPath).then(function(){

serveFile(indexHTMLPath,res);

},function(){

// Check if .html for the path exists

var plusHTMLPath = filePath +".html";

checkFilePath(plusHTMLPath).then(function(){

serveFile(plusHTMLPath,res);

},function(){

// Nope, does not exist at all

next();

});

});

});

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值