Sunday, 11 June 2017

How to add static file to http server?

I'd like to implement a chatroom by node.js.

I use the template provided by 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');
});

When I type

node index.js

in the terminal, it'll show up

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

Now, the server can work but the format is gone.

I don't know how to correct this. I hope that the chat.html can be in the format specified by the style.css and the messages can be sent in the format(also specified by the style.css) I desired not just pure text.



via walkcc

No comments:

Post a Comment