如何将静态文件添加到http服务器?

时间:2017-06-11 11:34:11

标签: javascript html node.js express

我想通过node.js实现一个聊天室。

我使用socket.io提供的模板。

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');

app.get('/', function(req, res) {
    fs.readFile(__dirname + '/style.css');    // I don't know how to import the style.css to the chat.html
    // fs.readFile(__dirname + '/images/');   // And how to add images file to the server
    res.sendFile(__dirname + '/chat.html');
});

io.on('connection', function(socket) {
    console.log('a user connected');
    socket.on('disconnect', function() {
        console.log('user disconnected');
    });
    socket.on('chat message', function(msg) {
        console.log('message: ' + msg);
    })
    socket.on('chat message', function(msg){
        io.emit('chat message', msg);
    });
    socket.broadcast.emit('hi');
});


http.listen(8888, function() {
    console.log('listening on *:8888');
});

当我输入

node index.js

在终端中,它会显示

listening on *:8888
(node:12873) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

现在,服务器可以正常工作,但格式已经消失。

我不知道如何纠正这个问题。我希望chat.html可以采用style.css指定的格式,并且消息可以以格式(也由style.css指定)发送。我希望不仅仅是纯文本。

1 个答案:

答案 0 :(得分:0)

您必须告诉节点您计划用于“静态文件”的目录。

你这样做

const staticCont = express.static(__dirname + "/public");

其中“public”是保存静态内容的文件夹的名称,如CSS或前端JS文件等。

希望这会有所帮助

相关问题