如何使用Node.js处理CSS?

时间:2013-04-03 21:50:06

标签: javascript node.js pug

我正在尝试使用直接的香草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);
}

页面加载很棒,我将其作为我的观察源:

<!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根本不起作用,我一直试图谷歌它,但每个答案似乎都使​​用快递或其他东西,但我想学习如何做到尽可能香草,所以我的问题是,我如何处理* .css以便正确加载css,当我点击视图源中的href链接时,它会加载我的404页面,而不仅仅是css文件的纯文本。谢谢!

随时可以在https://github.com/Gacnt/Node-Tests

查看回购

2 个答案:

答案 0 :(得分:1)

我设法通过创建一个处理静态页面的函数来解决我的问题,例如.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;

答案 1 :(得分:0)

为了处理.css和其他静态文件,需要有一个文件流。您可以使用以下内容,而不是使用switch语句。

var stream = fs.createReadStream(path); //创建文件流 stream.pipe(RES); //传输文件