使用node.js提供外部静态文件

时间:2015-07-08 18:43:03

标签: javascript node.js socket.io

我正在使用node.JS构建具有聊天功能的Web应用程序。我的服务器正在提供页面的基本内容,但我遇到了导入外部文件(如jpgs和样式表)的问题。这是我的主页的头部,包含我要导入的文件:

<head>
<meta charset="utf-8"/>
 <link rel="stylesheet" type="text/css" href="stylesheets/main.css" />
 <link href='http://fonts.googleapis.com/css?family=Alegreya+Sans' rel='stylesheet' type='text/css'>
 <link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
 <script src="/socket.io/socket.io.js"></script>
 <script type ="text/javascript">

  var socketio = io.connect();
  socketio.on("message_to_client",function(data) {
     //Append an HR thematic break and the escaped HTML of the new message
     document.getElementById("chatBox").appendChild(document.createElement("hr"));
     document.getElementById("chatBox").appendChild(document.createTextNode(data['message']));
  });

  function sendMessage(){
     var msg = document.getElementById("message_input").value;
     socketio.emit("message_to_server", {message:msg});
  }

这是我用来提供主页面和处理邮件的聊天服务器。我坚持让它来处理静态资源:

var http = require("http"),
socketio = require("socket.io"),
fs = require("fs"),
mime = require('mime');

var url = 'home.html';


var app = http.createServer(function(req, resp){

fs.readFile(url, function(err, data){

    if(err) return resp.writeHead(500);

    var mimeType = mime.lookup(url);
    resp.setHeader('Content-Type', mimeType);
    resp.writeHead(200);
    resp.end(data);
    });
});
app.listen(3456);

var io = socketio.listen(app);
io.sockets.on("connection", function(socket){
// This callback runs when a new Socket.IO connection is established.

socket.on('message_to_server', function(data) {
    // This callback runs when the server receives a new message from the client.

    console.log("message: "+data["message"]); // log it to the Node.JS output
    io.sockets.emit("message_to_client",{message:data["message"] }) // broadcast the message to other users
 });
});

1 个答案:

答案 0 :(得分:0)

为了提供静态文件,请执行此操作(我使用express,因此我添加了一个中间件来执行此操作)

在您的主应用文件中,添加此中间件:

app.use(express.static(__dirname + '/public')); //the argument is the location of the root directory with static files

其实就是这样。您的客户将获得路径/public

中托管的静态文件