Simple NodeJS Chat Program in Local Dev (MacOS)

April 2, 2021
# create directory for the node project
# init a new npm project
npm init

# install express server
npm i express

Open editor and add the chat server code:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
 res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
 console.log("user connected");
 socket.on("disconnect", function () {
 console.log("user disconnected")
 });

 socket.on('chat message', function(msg) {
 console.log("message: " + msg);
 io.emit('chat message', msg);
 });
});

http.listen(3000, function() {
 console.log("listening on 3000");
});

next, add the code for the webpage the server sends down

<html>
<body>
 <h1>Messages</h1>
 <ul id="messages"></ul>

 <form action="">
 <input id="m" type="text" />
 <input type="submit" />
 </form>

<script src="/socket.io/socket.io.js"></script>
 <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
 var socket = io();
 $('form').submit(function() {
 socket.emit('chat message', $("#m").val());
 $('#m').val('');
 return false;
 });
 socket.on('chat message', function(msg) {
 $("#messages").append($('<li>').text(msg))
 });
</script>
</body>

</html>


run the app

node appname.js

open multiple tabs in a web browser at the following address. Type chat messages and they will show up in all your tabs

http://localhost:3000
Personal Updates

This is a password protected section available to those who know me in some fashion. If you know me and you do not already have a login, you can request a login here.

Personal Updates
Book Reviews

I am nuts about books. I read on all kinds of topics. I attempt to review each book I read for the sake of my own enrichment as well as conversation starters with others.

My Book Reviews
Pastoral Ministry

God has called me to be a pastor, and occasionally I have some pastoral thoughts I like to share.

Pastoral Posts
The Attic

You never know what you will find in an attic! Usually there is a hodgepodge of things buried under dust.

Explore the Attic
Technology

Most of what is included here are notes to myself. The majority of folks will not find interest in these posts.

Technology Posts