gpt4 book ai didi

javascript - 如何使用 Node.js 处理 CSS?

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:04 24 4
gpt4 key购买 nike

我尝试只使用普通的Node.js,除了教育目的所需的框架之外,没有其他框架。我目前有这样的设置:

var fs = require('fs'),
jade = require('jade');

function compile(dirPath, res) {
var filePath = __dirname + dirPath;
fs.readFile(filePath, 'utf8', function(err, fd) {
var fn = jade.compile(fd, { filename: filePath, pretty: true});
res.write(fn());
res.end();
});

}

exports.compile = compile;

当请求所请求的页面时调用它,如下所示:

var jadec = require('./jadecompile');

function start(res, postData) {
res.writeHead(200, {"Content-Type": "text/html"});
var cpage = '/staticpages/index.jade',
page = jadec.compile(cpage, res);
}

页面加载得很好,我将此作为我的 View 源:

<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
<link rel="text/css" href="assets/css/bootstrap.css">
</head>
<body>
<div class="hero-unit">
<p>Hello This Is A Test</p>
</div>
</body>
</html>

但是CSS根本不起作用,我一直在尝试用谷歌搜索它,但每个答案似乎都使​​用express或其他东西,但我想学习如何尽可能简单地做到这一点,所以我的问题是,如何处理 *.css 以便正确加载 css,当我单击查看源中的 href 链接时,它会加载我的 404 页面,而不仅仅是纯文本CSS 文件。谢谢!

请随时查看存储库:https://github.com/Gacnt/Node-Tests

最佳答案

我设法通过创建一个函数来处理静态页面(例如 .css 或 .js)来解决我的问题,如下所示:

var http = require('http'),
url = require('url'),
path = require('path');
fs = require('fs');

// ADDED THIS FUNCTION HERE -----------------------------------------------------
function handleStaticPages(pathName, res) {
var ext = path.extname(pathName);
switch(ext) {
case '.css':
res.writeHead(200, {"Content-Type": "text/css"});
fs.readFile('./' + pathName, 'utf8', function(err, fd) {
res.end(fd);
});
console.log('Routed for Cascading Style Sheet '+ pathName +' Successfully\n');
break;
case '.js':
res.writeHead(200, {"Content-Type": "text/javascript"});
fs.readFile('./' + pathName, 'utf8', function(err, fd) {
res.end(fd);
});
console.log('Routed for Javascript '+ pathName +' Successfully\n');
break;
}
}
// ADDED THIS FUNCTION HERE -----------------------------------------------------

function start(route, handle) {
function onRequest(req, res) {
var postData = "",
pathName = url.parse(req.url).pathname;
console.log('Request for ' + pathName + ' received.');

req.addListener('data', function(data) {
postData += data;
console.log('Received POST data chunk ' + postData + '.');
});

req.addListener('end', function() {
var pathext = path.extname(pathName);
if (pathext === '.js' || pathext === '.css') {
handleStaticPages(pathName, res);
} else {
console.log('--> Routing only the view page');
route(handle, pathName, res, postData);
}
});
}

http.createServer(onRequest).listen(4000);
console.log('Server is now listening at: http://127.0.0.1:4000 .');
}

exports.start = start;

关于javascript - 如何使用 Node.js 处理 CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15798816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com