Hiển thị các bài đăng có nhãn NodeJS. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn NodeJS. Hiển thị tất cả bài đăng

Thứ Sáu, 4 tháng 2, 2022

NodeJS Express SocketIO – Chat message and send image

When it comes to NodeJS, Realtime must be thought of. Realtime here is to process the communication from client to server in real time.

NodeJS is an open source code widely used by thousands of programmers around the world. NodeJS can run on many different operating systems from Windows to Linux, OS X so that is also an advantage. NodeJS provides rich libraries in different form of Javascript Module which simplify programming and minimize time.

Here I will introduce the structure of realtime chat message application using NodeJS combined Express, Socket IO consists of two parts: server side, client side.


1. First, create a folder containing your source code and install modules.

– Create a folder containing your source code.

mkdir NodeJs-Express-SocketIO-SendImage

– Run [npm init] to initialize the source file, package.json. Select the js code file is index.js

cd NodeJs-Express-SocketIO-SendImage

npm init

– Install the module for use in NodeJS, it is: express ejs socketio

npm install express ejs socketio

– Now the content of your package.json file looks like this:

{
“name”: “NodeJs-Express-SocketIO-SendImage”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″
},
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“ejs”: “^3.1.6”,
“express”: “^4.17.1”,
“socketio”: “^1.0.0”
}
}

– Create a public folder to store js and images files after being uploaded.

mkdir public

cd public

mkdir js

mkdir uploads

– Copy jquery.min.js to public/js folder or you can get it from cdn jquery

– Your code directory will now look like this:

NodeJs-Express-SocketIO-SendImage-source-path

Source path


2. Server side NodeJS

– In the index.js file:

var express = require (‘express’);
var app = express();
var fs = require(‘fs’);

app.use(express.static(__dirname + ‘/public’));

app.set(“view engine”, “ejs”);
app.set(‘views’, ‘views’);

var server = require(‘http’).Server(app);

var io = require(‘socket.io’)(server);
const port = process.env.PORT || 8080;
server.listen(port, () => console.log(`Listen on port ${port}…`));

io.on(‘connection’, function (socket) {
console.log(‘Connection ID: ‘ + socket.id);
socket.on(‘disconnect’, function () {
console.log(‘Disconect ID: ‘ + socket.id);
});

// The server listens to data from the client
socket.on(‘Client-sent-data’, function (data) {
// After listening to data, server emit this data to all clients
io.sockets.emit(‘Server-sent-data’, data);
});

// Handle image
socket.on(“sendImage”, function(data){
var guess = data.base64.match(/^data:image\/(png|jpeg);base64,/)[1];
var ext = “”;
switch(guess) {
case “png”  : ext = “.png”; break;
case “jpeg” : ext = “.jpg”; break;
default     : ext = “.bin”; break;
}
var savedFilename = “/uploads/” + randomString(10)+ext;
fs.writeFile(__dirname + “/public” + savedFilename, getBase64Image(data.base64), ‘base64’, function(err) {
if (err !== null)
console.log(err);
else
io.sockets.emit(“receiveImage”, {
path: savedFilename,
});
console.log(“Send image success!”);
});
});
})

app.get(‘/’, function(req, res) {
res.render(‘home’);
})

function randomString(length)
{
var text = “”;
var possible = “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_”;

for( var i=0; i < length; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}

return text;
}

function getBase64Image(imgData) {
return imgData.replace(/^data:image\/(png|jpeg|jpg);base64,/, “”);
}


3. Client side NodeJS

– Use ejs to display Client side content. In the views folder, create home.ejs file

<!DOCTYPE html>
<html>
<head>
<title>NodeJS Express SocketIO – Chat message & send image</title>
<script type=”text/javascript” src=”js/jquery.min.js”></script>
<script type=”text/javascript” src=”socket.io/socket.io.js”></script>

<script type=”text/javascript”>
var socket = io(‘http://localhost:8080’);

// The client recevie the data from the server
socket.on(‘Server-sent-data’, function(data) {
$(‘#show-message’).append(‘<p>’ + data + ‘</p>’);
});

// The client send data to the server
$(document).ready(function () {
$(‘#send’).on(‘click’, function () {
var message = $(‘#message’).val();
socket.emit(“Client-sent-data”, message);
$(‘#message’).val(”);
document.getElementById(“message”).focus();
})

})

// Handle image
window.onload = function() {
document.getElementById(“file”).addEventListener(“change”, function(){
submitImage();
});
};

function submitImage(){
var selector = document.getElementById(“file”);
var img = document.getElementById(“preview”);

var reader = new FileReader();
reader.onload = function (e) {
// img.src = e.target.result;
// client send
socket.emit(“sendImage”, {base64:e.target.result});
}
reader.readAsDataURL(selector.files[0]);
}

// Client receive
socket.on(‘receiveImage’, function(data){
// document.getElementById(“showImage”).src = data.path;
var img = ‘<img id=”showImage” src=”‘ + data.path + ‘” width=”100″/>’;

$(‘#show-message’).append(img);
});
</script>
</head>

<body style=”width: 500px; margin: 0 auto;”>
<h2>Chat messages</h2>
<div id=”show-message”></div>
<div>
<p>
<textarea id=”message” rows=”5″ style=”width: 100%”></textarea>
</p>
<p>
Choose image:
<input id=”file” type=”file”>
<img id=”preview” width=”100″></img>
</p>

<button id=”send”>Send message</button>
</div>
</body>
</html>

 

And run in the browser:

NodeJs-Express-SocketIO-SendImage-client-side

Client side

 

4. Run demo NodeJS Express SocketIO, chat message and send image

– Now you run the web server using command: node index.js

node index.js

– Open two browsers to test, type in a message and choose a picture to send. When sending a message and selecting a photo in one of the screens, the received screen is also displayed

NodeJs-Express-SocketIO-SendImage-result

Result chat message

 

– In your command prompt

NodeJs-Express-SocketIO-SendImage-run

Result in console log

 

You check in the public/uploads folder, the images are saved.

Hope you guys get the basics of NodeJS, SocketIO and build yourself a simple real time app.

Tags: , , , , 

Thứ Ba, 1 tháng 2, 2022

NodeJS – Simple CRUD APIs with MySQL

In this article, I will do a simple CRUD APIs in NodeJS, Express and MySQL. We learn how to create restful (create, read, update, delete) api in NodeJS.

 

API End Points, test on Postman:

  • GET /learns: Give all learns stored in database
  • GET /learns/{id}: Give a specific user with id.
  • POST /learns : Create a record
  • PUT /learns/{id}: Update a record
  • DELETE /learns/{id}: Delete a record

 

Modules to install and use in this example:

  • express.js: Web framework express.
  • mysql: Node.js driver for MySQL.
  • body-parser: Converting the POST data into the request body.
  • nodemon: Automatically restart the server whenever the code changes.

 

1. Install the modules to use in NodeJS

Run [npm init] to initialize the source file, package.json. Select the js code file is index.js

npm init

Install these packages, type in the following command on Git Bash or your favorite cmd:

npm i –s express express-handlebars mysql body-parser

Installing nodemon with the global command:

npm i -g nodemon

 

We will have the following soure:

source-folder-method-get-list-nodejs-simple-crud-apis-with-mysql

Source folder

 

Package.json file content:

{
“name”: “nodemysql”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1″
},
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“body-parser”: “^1.19.0”,
“express”: “^4.17.1”,
“express-handlebars”: “^5.3.0”,
“mysql”: “^2.18.1”
}
}

 

2. MySQL Database

Create Database learns, with node_mysql_simple table as simple as follows:

// Schema: learns, DB: node_mysql_simple

CREATE DATABASE `learns` /*DEFAULT CHARACTER SET utf8 */;

CREATE TABLE `node_mysql_simple` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`course_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

database-method-get-list-nodejs-simple-crud-apis-with-mysql

MySQL Database

3. Index.js file server code

Use the required libraries that have been installed in NodeJS and establish a connection with MySQL.

const mysql = require(‘mysql’);
const express = require(‘express’);
const bodyparser = require(‘body-parser’);
var app = express();

// Express server
app.use(bodyparser.json());

// MySQL connection details
var mysqlConnection = mysql.createConnection({
host: ‘localhost’,
user: ‘root’,
password: ”,
database: ‘learns’,
multipleStatements: true
});

mysqlConnection.connect((err) => {
if (!err) {
console.log(‘Connect success.’);
} else {
console.log(‘Connect faile: ‘ + JSON.stringify(err, undefined, 2));
}
});

const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listen on port ${port}…`));

 

Now you run the web server using command: node index.js

node index.js

And your server is running at port 8080.

gitbash-command-nodejs-simple-crud-apis-with-mysql

Command run the web server

 

3.1. Insert data to Database, method POST route

var urlencodedParser = bodyparser.urlencoded({ extended: false });

// Post route value get from params
app.post(‘/learns’, urlencodedParser, (req, res) => {
let name = req.body.name;
let email = req.body.email;
let course_id = req.body.course_id;

let sql = “INSERT INTO node_mysql_simple (name, email, course_id) VALUES (?, ?, ?)”;
mysqlConnection.query(sql, [name, email, course_id], (err, rows, fields) => {
if (!err) {
res.send(‘Inserted ID : ‘ + rows.insertId);
} else {
console.log(err);
}
})
});

 

– Test on Postman: Input simple data with name, email. course_id.

method-post-method-get-list-nodejs-simple-crud-apis-with-mysql

Method Post

 

Or you can use MySQL insert multiple rows from array.

// Post route direct value
app.post(‘/learnDirect’, (req, res) => {
// Multi values
let values = [
[‘Amit’, ‘amit@gmail’, 1],
[‘Rishi’, ‘rishi@gmail’, 1],
[‘Akash’, ‘akash@gmail’, 1],
];

let sql = ‘INSERT INTO node_mysql_simple (name, email, course_id) VALUES ?’;
mysqlConnection.query(sql, [values], (err, rows, fields) => {
if (!err) {
res.send(‘Inserted ID ‘ + rows.insertId);
} else {
console.log(‘Error: ‘ + err);
}
});
});

3.2. Show data list and detail data with method GET route

– Get route list:

// Get route list
app.get(‘/learns’, (req, res) => {
mysqlConnection.query(‘SELECT * FROM node_mysql_simple’, (err, rows, field) => {
if (!err) {
res.send(rows);
} else {
console.log(‘Query error: ‘ + err);
}
})
});

 

After inserting the second record, we have the results, test on Postman:

method-get-list-nodejs-simple-crud-apis-with-mysql

Method Get, get data list

 

– Get route detail:

// Get route detail
app.get(‘/learns/:id’, (req, res) => {
mysqlConnection.query(‘SELECT * FROM node_mysql_simple WHERE id = ?’, [req.params.id], (err, row, field) => {
if (!err) {
res.send(row);
} else {
console.log(‘Query error: ‘ + err);
}
})
});

 

method-get-detail-nodejs-simple-crud-apis-with-mysql

Method Get, get detail on Postman

 

3.3. Update data with method PUT route

// Put route value get from params
app.put(‘/learns/:id’, urlencodedParser, (req, res) => {
let id = req.params.id;

let name = req.body.name;
let email = req.body.email;
let course_id = req.body.course_id;

let sql = “UPDATE node_mysql_simple SET name = ?, email = ?, course_id = ? WHERE id = ?”;
mysqlConnection.query(sql, [name, email, course_id, id], (err, rows, fields) => {
if (!err) {
res.send(‘Updated with ID : ‘+ id);
} else {
console.log(err);
}
})
});

 

method-update-nodejs-simple-crud-apis-with-mysql

Method Update

 

3.4. Delete data with method Delete

// Route Delete
app.delete(‘/learns/:id’, (req, res) => {
mysqlConnection.query(‘DELETE FROM node_mysql_simple WHERE id = ?’, [req.params.id], (err, rows, fields) => {
if (!err) {
res.send(‘Delete success ID: ‘ + req.params.id);
} else {
console.log(‘Delete error: ‘ + err);
}
})
});

 

method-delete-nodejs-simple-crud-apis-with-mysql

Method Delete

 

– Maybe you are interested: PHP – MVC CRUD and Connect to MySQL using PDO

 

Thank for reading.