如何在node.js中创建静态文件(.css,.js)(仅限node.js)

时间:2016-05-26 09:03:42

标签: javascript html css node.js static-files

问题,我正在开发node.js应用。简单没有单一的应用。我在app.js文件中完成了一些事情..但是node.js没有加载我的.css文件和.js文件。

我用.css和.js文件修复了

没有加载我得到了回来。但我需要输出文件中的文件不在公共/文件夹中。

想要解决它。我的页面看起来也变成了这个,但是源代码没有加载css样式表或javascript文件。我不知道为什么?

我的结构:

-css
  --style.css
-js
  --javascript.js
-app.js  
-public
 --index.html
 --add.html

这是我的代码:

var http = require('http');
var fs = require('fs');


http.createServer(function(request, response) {
        console.log('request starting...');

    var url = request.url;
    switch(url) {
        case '/' :
            getStaticFileContent(response, 'public/index.html','text/html');
            break;
        case '/add':
            getStaticFileContent(response, 'public/add.html','text/html');
            break;
        case '/css':
            getStaticFileContent(response, 'css/style.css','text/css');
            break;
        case '/js':
            getStaticFileContent(response, 'js/javascript.js','text/javascript');
            break;
        default:

        response.writeHead(404, {'Content-Type':'text/plain'});
        response.end('404 - Page not Found');
}

}).listen(8000);
console.log('Hello World, this is the   Projekt Nr.1');
console.log('Server Running at localhost:80');


function getStaticFileContent(response, filepath, contentType) {
    fs.readFile(filepath, function(error, data){
        if(error) {
            response.writeHead(500,{'Content-Type':'text/plain'});
            response.end('500 - Internal Server Error');
    }
    if(data) {
            response.writeHead(500,{'Content-Type':'text/html'});
            response.end(data);
        }
    });
}

2 个答案:

答案 0 :(得分:1)

这里是新的...最后如果用else做的话:

td

答案 1 :(得分:0)

使用类似于Web应用程序的快捷框架。所以在express express.static中会注意为客户端提供静态文件。

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

app.use(express.static( '公共'));

将所有静态文件放在公共目录中,express表示将服务。