Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Tutorial NodeJS

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Node JS File Upload using express-fileupload Module

November 4, 2020Node JS <head>


<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
In this Node js file upload tutorial, you will learn how to upload files into the server <title>Node JS File Upload - W3jar.Com</title>
using Node JS with the express-fileupload module. <style>
Content of Node JS File Upload body{
 Simple file upload padding: 0;
 Limiting the upload size margin: 0;
 Rename the file before uploading font-family: Arial, Helvetica, sans-serif;
 Upload only specific types of files (Such as Only images allowed to be }
uploaded)
✍ Before getting started .container{
First, create a new folder on your desktop called node-file-upload, the name is max-width: 400px;
completely up to you, basically, this is our app folder. margin: 0 auto;
After that, go inside the app folder and initialize the npm, and then you have to install padding: 20px;
two packages – text-align: center;
1. express Framework }
2. express-fileupload
Run the following command to install the above two packages – [type="file"]{
npm i express express-fileupload border: 1px solid #cccccc;
After installing the package, my package.json folder looks like the following. background: #f9f9f9;
{ width: 100%;
"name": "node-file-upload", padding: 10px;
"version": "1.0.0", margin-bottom: 10px;
"description": "", font-size: 18px;
"main": "index.js", border-radius: 2px;
"scripts": { }
"test": "echo \"Error: no test specified\" && exit 1" [type="submit"]{
}, cursor: pointer;
"author": "W3jar.Com", font-size: 16px;
"license": "ISC", background: #5d13e7;
"dependencies": { color: #ffffff;
"express": "^4.17.1", padding: 10px 20px;
"express-fileupload": "^1.2.0" border: 1px solid rgba(0,0,0,.1);
} border-radius: 3px;
} box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
Now in the root of the app folder, you have to create a folder called ????uploads. Inside }
the uploads folder, the uploaded file will be stored.
Again in the root of the app folder, you have to create index.html for the file </style>
upload HTML Form. </head>
index.html <body>
<!DOCTYPE html> <div class="container">
<html lang="en"> <h1>Node.js File Upload</h1>

1
return res.status(400).send('No files were uploaded.');
<form action="" method="POST" enctype="multipart/form-data"> }
<input type="file" name="target_file" required>
<input type="submit" value="Upload"> // Accessing the file by the <input> File name="target_file"
</form> let targetFile = req.files.target_file;

</div> //mv(path, CB function(err))


</body> targetFile.mv(path.join(__dirname, 'uploads', targetFile.name), (err) => {
</html> if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});

});

app.listen(3000, () => console.log('Your app listening on port 3000'));

Limiting the upload size


In the following code, the maximum upload size is 1MB
index.js
const express = require('express');
const fileUpload = require('express-fileupload');
HTML Form in Browser
const fs = require('fs');
const path = require('path');
Simple Node JS File Upload const app = express();
index.js
const express = require('express'); app.use(fileUpload({
const fileUpload = require('express-fileupload'); useTempFiles : true,
const path = require('path'); tempFileDir : path.join(__dirname,'tmp'),
const app = express(); }));

app.use(fileUpload({ app.get('/', (req, res) => {


useTempFiles : true, res.sendFile(path.join(__dirname, 'index.html'));
tempFileDir : path.join(__dirname,'tmp'), });
}));
app.post('/', (req, res) => {
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
if (!req.files || Object.keys(req.files).length === 0) {
});
return res.status(400).send('No files were uploaded.');
}
app.post('/', (req, res) => {
let targetFile = req.files.target_file;
if (!req.files || Object.keys(req.files).length === 0) {

2
// Checking File Size (Max Size - 1MB)
if(targetFile.size > 1048576){ let targetFile = req.files.target_file;
let extName = path.extname(targetFile.name);
// Deleting Temporary File let baseName = path.basename(targetFile.name, extName);
fs.unlinkSync(targetFile.tempFilePath); let uploadDir = path.join(__dirname, 'uploads', targetFile.name);
return res.status(413).send("File is too Large");
} if(targetFile.size > 1048576){
fs.unlinkSync(targetFile.tempFilePath);
targetFile.mv(path.join(__dirname, 'uploads', targetFile.name), (err) => { return res.status(413).send("File is too Large");
if (err) }
return res.status(500).send(err);
res.send('File uploaded!'); // Renaming the file
}); let num = 1;
while(fs.existsSync(uploadDir)){
}); uploadDir = path.join(__dirname, 'uploads', baseName + '-' + num + extName);
num++;
app.listen(3000, () => console.log('Your app listening on port 3000')); }

targetFile.mv(uploadDir, (err) => {


Rename the file before uploading if (err)
In the following example, we will rename those files that already exist in the ???? return res.status(500).send(err);
uploads folder with the same name and extension. So that the new file cannot replace res.send('File uploaded!');
the old file. });
index.js
const express = require('express'); });
const fileUpload = require('express-fileupload');
const fs = require('fs'); app.listen(3000, () => console.log('Your app listening on port 3000'));
const path = require('path');
const app = express();
Upload only specific types of files
app.use(fileUpload({ In the following example, we will be allowed to upload only images. Such as – png, jpg,
useTempFiles : true, jpeg, gif
tempFileDir : path.join(__dirname,'tmp'), index.js
})); const express = require('express');
const fileUpload = require('express-fileupload');
app.get('/', (req, res) => { const fs = require('fs');
res.sendFile(path.join(__dirname, 'index.html')); const path = require('path');
}); const app = express();

app.post('/', (req, res) => { app.use(fileUpload({


useTempFiles : true,
if (!req.files || Object.keys(req.files).length === 0) { tempFileDir : path.join(__dirname,'tmp'),
return res.status(400).send('No files were uploaded.'); }));
}

3
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
CRUD RESTful API using Node.js
}); (Express.js) and MySQL Database
July 22, 2020Node JS Projects
app.post('/', (req, res) => {
Node JS (Express JS, MySQL) CRUD RESTful API
if (!req.files || Object.keys(req.files).length === 0) { Here we are going to create a simple CRUD RESTful API
return res.status(400).send('No files were uploaded.'); using Node.js with Express.js Framework and MySQL Database.
} And through this RESTful API, we will be inserting user name and email address
into the MySQL Database (Instead of the MySQL DB, You can also use the
let targetFile = req.files.target_file; MariaDB.).
let extName = path.extname(targetFile.name); The purpose of this tutorial is to give an idea of creating RESTful APIs using Node JS.
let baseName = path.basename(targetFile.name, extName);
let uploadDir = path.join(__dirname, 'uploads', targetFile.name);
Follow the below steps to create this Node.JS CRUD RESTful API
1) Database Setup
let imgList = ['.png','.jpg','.jpeg','.gif'];
First of all, we have to create our database and database table where we will store
// Checking the file type
user information. In the following, the database information is given –
if(!imgList.includes(extName)){
 Database Name – node_restful_api
fs.unlinkSync(targetFile.tempFilePath);
return res.status(422).send("Invalid Image");  Table name – users
} Now open your MySQL DB or MariaDB and create a new database
called node_restful_api. And after creating this DB, use the following SQL code to
if(targetFile.size > 1048576){ create the `users` table and the structure of this table –
fs.unlinkSync(targetFile.tempFilePath); SQL Code for `users` table
return res.status(413).send("File is too Large"); CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
} `name` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
let num = 1; PRIMARY KEY (`id`),
while(fs.existsSync(uploadDir)){ UNIQUE KEY `email` (`email`)
uploadDir = path.join(__dirname, 'uploads', baseName + '-' + num + extName); ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
num++;
} 2) Node JS env setup & installing node packages
After completing the Database configuration, create a new folder on your Desktop,
targetFile.mv(uploadDir, (err) => { and name it whatever you want. Here I named it node-rest-api.
if (err) Now go inside the node-rest-api folder and initialize the NPM with the help of
return res.status(500).send(err); the npm init command.
res.send('File uploaded!'); After that, you have to install some Node Packages to create this application in my
}); way. Use the following command to install those packages at once –
npm install --save express express-validator mysql2
}); After installing the above node packages my package.json file looks like the
app.listen(3000, () => console.log('Your app listening on port 3000')); following –
package.json
{
"name": "node-restful-api",
"version": "1.0.0",
4
"description": "",
"main": "index.js", After making the Database connection, now we will create the validator.js for
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1" validating the request data.
}, To validating the requested data we will use the express-validator package. So if
"author": "Chandan Tudu", don’t know how to use this package to validate the requested data, then check out
"license": "ISC", the following tutorial –
"dependencies": {  Validate form data in Node JS (Express JS) with express-validator package
"express": "^4.17.1",
validator.js
"express-validator": "^6.6.0",
const db_connection = require("./db-connection").promise();
"mysql2": "^2.1.0"
const { body, param, validationResult } = require("express-validator");
}
}
module.exports = {
// User name and email Validation
3) Creating files & folders userInfo: [
Now time to create the application files & folders. But, before going further, let’s body("name", "The name must be of minimum 3 characters length")
have a look at the node-rest-api folder structure. See the below image – .optional()
.isLength({ min: 3 })
.trim()
.unescape()
.escape(),

body("email", "Invalid email address")


.optional()
.trim()
.unescape()
.escape()
.isEmail()
.custom(async (value) => {
// Checking that the email already in use or NOT
const [row] = await db_connection.execute(
"SELECT `email` FROM `users` WHERE `email`=?",
[value]
node-rest-api folder structure );
First, we will create the db-connection.js to create the MySQL database connection. if (row.length > 0) {
return Promise.reject("E-mail already in use");
db-connection.js
}
const mysql = require("mysql2");
}),
],
const db_connection = mysql
.createConnection({
// User ID Validation
host: "localhost", // HOST NAME
userID: [param("id", "Invalid User ID").trim().isInt()],
user: "root", // USER NAME
database: "node_restful_api", // DATABASE NAME
// Checking Validation Result
password: "", // DATABASE PASSWORD
result: (req, res, next) => {
})
const errors = validationResult(req);
.on("error", (err) => {
if (!errors.isEmpty()) {
console.log("Failed to connect to Database - ", err);
return res.status(422).json({ errors: errors.array() });
});
}
next();
module.exports = db_connection;
},
5
}; After creating the user routes, now we will create a controller for the routes. This
controller is for handling user routes, that’s why we’ll name it userController.js.
For separating the controllers, we will create a new folder called controllers in the
Now we will create the routes.js for specifying the API endpoints. root of the application folder. And inside this folder, we have to create
routes.js the userController.js.
const router = require('express').Router(); userController.js
const validators = require('./validators'); const db_connection = require("../db-connection").promise();
const userController = require('./controllers/userController');
// INSERTING USER
// Inserting User exports.insert = async (req, res, next) => {
router.post(
'/insert-user', if (!req.body.name || !req.body.email) {
validators.userInfo, return res.status(400).json({
validators.result, message: "Please fill in all the required fields.",
userController.insert fields: ["name", "email"],
); });
}
// Fetching all users
router.get( try {
'/get-all-users',
userController.getAllUsers
const [rows] = await db_connection.execute(
);
"INSERT INTO `users`(`name`,`email`) VALUES(?, ?)",
[req.body.name, req.body.email]
// Fetching Single User By ID
);
router.get(
'/get-user/:id',
if (rows.affectedRows === 1) {
validators.userID,
return res.status(201).json({
validators.result,
message: "The user has been successfully inserted.",
userController.getUserByID
userID: rows.insertId,
);
});
}
// Updating User
router.patch(
} catch (err) {
'/update-user/:id',
next(err);
[...validators.userID, ...validators.userInfo],
}
validators.result,
userController.updateUser
); };

// FETCHING ALL USERS


// Deleting User
exports.getAllUsers = async (req, res, next) => {
router.delete(
try {
'/delete-user/:id',
validators.userID,
const [rows] = await db_connection.execute("SELECT * FROM `users`");
validators.result,
userController.deleteUser
if (rows.length === 0) {
);
return res.status(200).json({
message:
module.exports = router;
"There are no users in the database, please insert some users.",
});
}
6
if (req.body.email) row[0].email = req.body.email;
res.status(200).json(rows);
const [update] = await db_connection.execute(
} catch (err) { "UPDATE `users` SET `name`=?, `email`=? WHERE `id`=?",
next(err); [row[0].name, row[0].email, req.params.id]
} );

}; if (update.affectedRows === 1) {
return res.json({
message: "The User has been successfully updated.",
// FETCHING SINGLE USER });
exports.getUserByID = async (req, res, next) => { }

try { } catch (err) {


next(err);
const [row] = await db_connection.execute( }
"SELECT * FROM `users` WHERE `id`=?",
[req.params.id] };
);
// DELETING USER
if (row.length === 0) { exports.deleteUser = async (req, res, next) => {
return res.status(404).json({
message: "No User Found!", try {
});
} const [row] = await db_connection.execute(
"DELETE FROM `users` WHERE `id`=?",
res.status(200).json(row[0]); [req.params.id]
);
} catch (err) {
next(err); if (row.affectedRows === 0) {
} return res.status(404).json({
message: "Invalid user ID (No User Found!)",
}; });
}
// UPDATING USER
exports.updateUser = async (req, res, next) => { res.status(200).json({
try { message: "The user has been deleted successfully.",
});
const [row] = await db_connection.execute(
"SELECT * FROM `users` WHERE `id`=?", } catch (err) {
[req.params.id] next(err);
); }
if (row.length === 0) { };
return res.status(404).json({
message: "Invalid User ID",
}); At the end of the files and folder creation, we will create the index.js, where we will
} create the server, apply routes middleware, and handling errors.
index.js
if (req.body.name) row[0].name = req.body.name; const express = require("express");
const app = express();

7
const allRoutes = require("./routes");

// It parses incoming requests with JSON payloads


app.use(express.json());

// Applying All Routes


app.use(allRoutes);

// Handling Errors
app.use((err, req, res, next) => {
// console.log(err);
err.statusCode = err.statusCode || 500;
err.message = err.message || "Internal Server Error";
res.status(err.statusCode).json({
message: err.message,
});
});

app.listen(3000, () => console.log("Server is running on port 3000"));

Testing of the Node.js CRUD RESTful API Application


First, start the server by running the nodemon index command and also make sure Inserting User
that your MySQL server is also running.
To test this API application I will use the Postman. Getting all users
API URLs –
POST - http://localhost:3000/insert-user GET - http://localhost:3000/get-all-users

GET - http://localhost:3000/get-all-users

GET - http://localhost:3000/get-user/{user_id}

PATCH - http://localhost:3000/update-user/{user_id}

DELETE - http://localhost:3000/delete-user/{user_id}

Inserting User

POST - http://localhost:3000/insert-user

8
Fetching all users Result after updating the user

Getting single user by ID

GET - http://localhost:3000/get-user/{user_id}

Result after updating the user

Deleting the user whose ID is 1

DELETE - http://localhost:3000/delete-user/{user_id}
Fetching single user by ID

Updating User (id=1)

PATCH - http://localhost:3000/update-user/{user_id}

Deleting User 1

Result after deleting the user 1

Updating User

9
Result after deleting the user

10
Node JS Form Handling: GET, POST Requests, Form Data Validation Params Example (index.js)
December 20, 2020Node JS const express = require('express');
const app = express();
In this Node JS Form Handling tutorial, you will learn how to get Form data
through the GET and POST requests, and how to validate the form data (Form app.get('/test/:id', (req,res) => {
console.log(`The ID is - ${req.params.id}`);
Validation).
res.send('Check the console');
Content of Form Handling in Node.js });
 GET Request
 URL Params app.listen(3000, () => console.log('Your app listening on port 3000'));
 POST Request
 JSON Payload http://localhost:3000/test/21
 Form Validation
The ID is - 21
✍ Before getting started
In this tutorial, we will use Express.js framework. So frist,  create a new folder on
POST Request in Node JS
your desktop called node-form-handling, the name is completely up to you, basically,
If you want to get the data requested from the POST method, you have to use
this is our app folder.
the express.urlencoded() middleware.
After that, go inside the app folder and initialize the npm, and then you have to
After applying the middleware, now you can access the post data using req.body
install the express.js (use the following the command to install it)–
npm i express POST Example (index.js)
const express = require('express');
const app = express();
GET Request in Node JS
You can access GET requested data using – req.query // Applying the middleware
GET Example (index.js) app.use(express.urlencoded({extended:false}));
const express = require('express');
const app = express(); app.get('/', (req, res) => {
// HTML Form (POST Method)
app.get('/', (req, res) => { res.send(`<form action="/test" method="POST">
// HTML Form <label>Username</label><br>
res.send(`<form action="/test" method="GET"> <input type="text" name="username" placeholder="Enter Username"><br>
<label>Username</label><br> <label>Password</label><br>
<input type="text" name="username" placeholder="Enter Username"><br> <input type="password" name="pass" placeholder="Enter Password"><br><br>
<label>Password</label><br> <input type="submit">
<input type="password" name="pass" placeholder="Enter Password"><br><br> </form>`);
<input type="submit"> });
</form>`);
}); app.post('/test', (req,res) => {
console.log(req.body);
app.get('/test', (req,res) => { res.send('Check the console');
//Displaying the GET data in console });
console.log(req.query);
res.send('Check the console'); app.listen(3000, () => console.log('Your app listening on port 3000'));
});
JSON payload in Node JS
app.listen(3000, () => console.log('Your app listening on port 3000')); But, if you want to request the data through the REST API with JSON payload,
then you have to apply the express.json() middleware.
Parse URL params value in Node JS JSON Payload (index.js)
You can parse the URL params data using – req.params const express = require('express');
11
const app = express();
//<input type="text" name="user_email">
app.use(express.json()); body('user_email').isEmail(),

app.post('/test', (req,res) => { (req,res) => {


res.json({
"data_from_server":{ const validation_result = validationResult(req);
...req.body
} if(validation_result.isEmpty()){
}); res.send('All is ok');
}); }
else{
app.listen(3000, () => console.log('Your app listening on port 3000')); //User has entered some invalid input values
console.log(validation_result.array());
Form Validation in Node JS }
In this tutorial, we will use the express-validator package to validate the form data. });
This package is a set of express.js middlewares that wraps validator.js validator The array() method returns an array of objects, which includes all the fields that are
and sanitizer functions. incorrectly filled in by a user.
Installation of express-validator [
npm i express-validator {
Use of express-validator value: 'test',
After installing that, import the body, validationResult from that package. msg: 'Invalid value',
const {body, validationResult} = require('express-validator'); param: 'user_email',
The body() is used as a middleware to validate the form fields. This method takes location: 'body'
}
the name of the input field.
]
isEmail() it is an inbuilt method to validate an email address, and in the validator.js, Array of body() middlewares
there are lots of inbuilt methods to validate other types of fields. You can add multiple body middlewares in an array for validating multiple input
app.post('/test',
fields.
//<input type="text" name="user_email"> app.post('/test',
body('user_email').isEmail(),
/* <form>
(req,res) => { <input type="text" name="user_email">
<input type="text" name="number">
const validation_result = validationResult(req); </form> */
[
}); body('user_email').isEmail(),
body('number').isNumeric()
The validationResult method returns the validation results, basically, it returns the
],
five methods. But, we only need two methods to validate the form data
– isEmpty() and array() (req,res) => {
1. isEmpty()
2. array() const validation_result = validationResult(req);
3. mapped()
});
4. formatWith()
Set custom error message (msg)
5. throw()
The second parameter of the body() method is for adding custom error message.
The isEmpty() method returns FALSE, if the validation fails, else it will return TRUE. body('user_email','Invalid email address').isEmail(),
app.post('/test', Apply multiple validations in one field
12
You can implement multiple validations in a field by chaining the validation This express-validator package is also allowed to create custom validators, and this
methods. makes the package more powerful and interesting.
body('number').isNumeric().isLength({min:5,max:10}), The custom() method is used to create a custom validator. This method takes a call
Full Code back function and the call back function takes a parameter to access the input field
const express = require('express'); value.
const {body, validationResult} = require('express-validator'); app.post('/',
const app = express(); body('user_email').custom((value) => {
// This is user email.
app.use(express.urlencoded({extended:false})); console.log(value);
})
app.get('/', (req,res) => { );
res.send(`<form action="/test" method="POST">
You can also access the request (req) inside the callback function –
<label>Email</label><br>
app.post('/',
<input type="text" name="user_email" placeholder="Enter email"><br>
body('user_email').custom((value,{req}) => {
<label>Password</label><br>
<input type="password" name="pass" placeholder="Enter password"><br><br>
<input type="submit"> // requests
</form>`); console.log(req)
}); })
);
app.post('/test', Example of Custom Validator
[ The following example checks the main Password matches the confirmation-
body('user_email', 'Invalid email address').isEmail(), password.
body('pass', 'Password must be between 5 and 10 characters').isLength({min:5,max:10}), If the password matches the confirm password, it will return TRUE, else it will throw
],
the dose not match error.
app.post('/test',
(req,res) => {
[
body('pass', 'Password must be between 5 and 10 characters').isLength({min:5,max:10}),
const validation_result = validationResult(req);
body('confirmation_pass').custom((value, {req}) => {
if (value !== req.body.pass) {
if(validation_result.isEmpty()){
throw new Error('Password and confirm password does not match');
}
res.send('All is ok');
return true;
}
}),
else{
],
let sendError = '';
(req,res) => {
validation_result.array().forEach((error) => {
// Handle the request
sendError += ' <br>' + error.msg;
});
});
Full Code
res.send(sendError); const express = require('express');
} const {body, validationResult} = require('express-validator');
const app = express();
});
app.use(express.urlencoded({extended:false}));
app.listen(3000, () => console.log('Your app listening on port 3000'));
app.get('/', (req,res) => {
res.send(`<form action="/test" method="POST">
Make a custom validator <label>Password</label><br>

13
<input type="password" name="pass" placeholder="Enter password"><br>
<label>Confirmation Password</label><br>
<input type="password" name="confirmation_pass" placeholder="Confirmation
Password"><br><br>
<input type="submit">
</form>`);
});

app.post('/test',
[
body('pass', 'Password must be between 5 and 10 characters').isLength({min:5,max:10}),
How to Update Data of MySQL
body('confirmation_pass').custom((value, {req}) => {
if (value !== req.body.pass) {
throw new Error('Password and confirm password does not match');
Database Using Node JS
} October 26, 2019 Node JS
return true; Here you will learn how to Update Data of MySQL Database Using Node JS. To
}), Update Data of MySQL Database, we will use the mysql2 module.
], But, before going further, I suggest you first check out this –
(req,res) => {  Create MySQL Database Connection with Node JS
 How to Query a MySQL Database using Node JS
const validation_result = validationResult(req);  Insert Data Into MySQL Database Using Node JS
 Fetch (Select) Data From MySQL Database Using Node JS
if(validation_result.isEmpty()){

res.send('All is ok'); Database Configuration


Database Name – test
} Table Name – users
else{ So first, Strat your MySQL Server and create a Database called test, and then inside
let sendError = ''; the test database create a table called users.
validation_result.array().forEach((error) => { Use the following SQL Code to create users table and the structure of the users table.
sendError += ' <br>' + error.msg; CREATE TABLE `users` (
}); `id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
res.send(sendError); `age` int(11) NOT NULL,
} `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
}); ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci;
app.listen(3000, () => console.log('Your app listening on port 3000'));
Database Connection

const mysql = require('mysql2');


const db_connection = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
password:'your_db_password'

14
});

Update Data of MySQL Database


Updating User

let _new_name = "Adam Smith";

db_connection.promise()
.execute("UPDATE `users` SET `name`=? WHERE `id`=?",[_new_name, 1])
.then(([result]) => {
//console.log(result);
if(result.affectedRows === 1){
How to Delete Data From MySQL
}
console.log("User Successfully Updated.");
Database Using Node JS
}).catch(err => { October 26, 2019Node JS
console.log(err);
}); Here you will learn how to Delete Data from MySQL Database Using Node JS. To
Delete Data from MySQL Database, we will use the mysql2 module.
Full Code of Update Data But, before going further, I suggest you first check out this –
Full code  Create MySQL Database Connection with Node JS
 How to Query a MySQL Database using Node JS
const mysql = require('mysql2');
const db_connection = mysql.createPool({  Insert Data Into MySQL Database Using Node JS
host: 'localhost',  Fetch (Select) Data From MySQL Database Using Node JS
user: 'root',  Update Data of MySQL Database Using Node JS
database: 'test',
password:'your_db_password'
Database Configuration
});
Database Name – test
let _new_name = "Adam Smith"; Table Name – users
So first, Strat your MySQL Server and create a Database called test, and then inside
db_connection.promise() the test database create a table called users.
.execute("UPDATE `users` SET `name`=? WHERE `id`=?",[_new_name, 1])
Use the following SQL Code to create users table and the structure of the users table.
.then(([result]) => {
//console.log(result);
if(result.affectedRows === 1){ CREATE TABLE `users` (
console.log("User Successfully Updated."); `id` int(11) NOT NULL AUTO_INCREMENT,
} `name` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
}).catch(err => { `age` int(11) NOT NULL,
console.log(err); `email` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
}); PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci;

Database Connection

const mysql = require('mysql2');


const db_connection = mysql.createPool({
host: 'localhost',
15
user: 'root',
database: 'test',
password:'your_db_password'
});

Delete Data of MySQL Database


Deleting User
db_connection.promise()
.execute("DELETE FROM `users` WHERE `id`=?",[1])
.then(([result]) => {
if(result.affectedRows === 1){
console.log("User Successfully Deleted.");
}
}).catch(err => {
console.log(err);
});

Full Code of Delete Data


Full Code of Deleting User

const mysql = require('mysql2');


const db_connection = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
password:'your_db_password'
});

db_connection.promise()
.execute("DELETE FROM `users` WHERE `id`=?",[1])
.then(([result]) => {
if(result.affectedRows === 1){
console.log("User Successfully Deleted.");
}
}).catch(err => {
console.log(err);
});

16

You might also like