repl.it
@Coder100/

Express chat

Nodejs

No description

fork
loading
Files
  • index.js
  • app
  • Packager files
  • package-lock.json
  • package.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var express = require("express");
var app = express();
var fs = require("fs");
var __dirname = fs.realpathSync(".");
var bodyParser = require('body-parser');
var chat = {
  messages: [
    {
      name: "Junhao",
      message: "Hello everyone!",
    },
    {
      name: "Mr. Oof",
      message: "Kewl!",
    },
    {
      name: "Mr. Oof",
      message: "Oof, I tripped again (my 194034th trip today)",
    },
  ]
};
var bchat = require(__dirname+"/app/chat.json");
for(var i = 0; i < chat.messages.length; i ++){
  var a = chat.messages[i].name;
  var g = chat.messages[i].message;
  a = a.replace(/([\"|\'])/gi, "\\$1");
  g = g.replace(/([\"|\'])/gi, "\\$1");
}
app.use(bodyParser.urlencoded({ extended: true }));
fs.writeFile(__dirname+"/app/chat.json", JSON.stringify(chat), "utf-8", function(err){if(err) throw err;});
app.get("/", function(req, res){
    fs.readFile(__dirname+'/app/index.html','utf-8', function(err, data){
    if (err) throw err;
      res.send(data+`
      <script>
        var chat = ${JSON.stringify(bchat)};
        \$(".chat").html("");
        for(var i = 0; i < chat.messages.length; i ++){
          \$(".chat").append(chat.messages[i].name+" said: "+chat.messages[i].message+"<br>");
        }
      </script>`);
    });
}).listen(8080);
app.use("/logo",express.static(__dirname+"/app/logo.png"));
app.use("/favicon.ico",express.static(__dirname+"/app/logo.png"));
app.get("/test.json", function(req, res){
  res.send(getchat);
});
app.post("/msg", function(req, res){
  var a = req.body.name;
  var b = req.body.message;
  bchat.messages.push({name: a, message: b});
  fs.writeFile(__dirname+"/app/chat.json", JSON.stringify(bchat), "utf-8", function(err){if(err) throw err;});
  console.log(bchat);
  console.log(chat);
  res.send(bchat.messages[bchat.messages.length-2].message+"<script>window.location='/';</script>");
});
?