Create Connection
Start by creating a connection to the database.
Use the username and password from your
MySQL database.
demo_db_connection.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Run example »
Query a Database
Use SQL statements to read from (or write to) a
MySQL database. This is also called "to query" the
database.
The connection object created in the example
above, has a method for querying the database:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Result: " + result);
});
});
Creating a Database
To create a database in MySQL, use the "CREATE
DATABASE" statement:
Example
Create a database named "mydb":
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE
mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
Creating a Table
To create a table in MySQL, use the "CREATE
TABLE" statement.
Make sure you define the name of the database
when you create the connection:
ExampleGet your own Node.js Server
Create a table named "customers":
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (name
VARCHAR(255), address VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
Run example »
Save the code above in a file called
"demo_create_table.js" and run the file:
Run "demo_create_table.js"
C:\Users\Your Name>node demo_create_table.js
Which will give you this result:
Connected!
Table created
Primary Key
When creating a table, you should also create a
column with a unique key for each record.
This can be done by defining a column as "INT
AUTO_INCREMENT PRIMARY KEY" which will
insert a unique number for each record. Starting
at 1, and increased by one for each record.
Example
Create primary key when creating the table:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (id INT
AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(255), address VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
Run example »
If the table already exists, use the ALTER TABLE
keyword:
Example
Create primary key on an existing table:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "ALTER TABLE customers ADD COLUMN
id INT AUTO_INCREMENT PRIMARY KEY";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table altered");
});
});
Insert Into Table
To fill a table in MySQL, use the "INSERT INTO"
statement.
ExampleGet your own Node.js Server
Insert a record in the "customers" table:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name,
address) VALUES ('Company Inc', 'Highway 37')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
Run example »
Save the code above in a file called
"demo_db_insert.js", and run the file:
Run "demo_db_insert.js"
C:\Users\Your Name>node demo_db_insert.js
Which will give you this result:
Connected!
1 record inserted
Insert Multiple Records
To insert more than one record, make an array
containing the values, and insert a question mark
in the sql, which will be replaced by the value
array:
INSERT INTO customers (name, address) VALUES ?
Example
Fill the "customers" table with data:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name,
address) VALUES ?";
var values = [
['John', 'Highway 71'],
['Peter', 'Lowstreet 4'],
['Amy', 'Apple st 652'],
['Hannah', 'Mountain 21'],
['Michael', 'Valley 345'],
['Sandy', 'Ocean blvd 2'],
['Betty', 'Green Grass 1'],
['Richard', 'Sky st 331'],
['Susan', 'One way 98'],
['Vicky', 'Yellow Garden 2'],
['Ben', 'Park Lane 38'],
['William', 'Central st 954'],
['Chuck', 'Main Road 989'],
['Viola', 'Sideway 1633']
];
con.query(sql, [values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " +
result.affectedRows);
});
});
ExampleGet your own Node.js Server
Select all records from the "customers" table, and
display the result object:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM
customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Run example »
SELECT * will return all columns
Save the code above in a file called
"demo_db_select.js" and run the file:
Run "demo_db_select.js"
C:\Users\Your Name>node demo_db_select.js
Which will give you this result:
[
{ id: 1, name: 'John', address: 'Highway 71'},
{ id: 2, name: 'Peter', address: 'Lowstreet 4'},
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 5, name: 'Michael', address: 'Valley 345'},
{ id: 6, name: 'Sandy', address: 'Ocean blvd 2'},
{ id: 7, name: 'Betty', address: 'Green Grass 1'},
{ id: 8, name: 'Richard', address: 'Sky st 331'},
{ id: 9, name: 'Susan', address: 'One way 98'},
{ id: 10, name: 'Vicky', address: 'Yellow Garden
2'},
{ id: 11, name: 'Ben', address: 'Park Lane 38'},
{ id: 12, name: 'William', address: 'Central st
954'},
{ id: 13, name: 'Chuck', address: 'Main Road
989'},
{ id: 14, name: 'Viola', address: 'Sideway 1633'}
]
Selecting Columns
To select only some of the columns in a table, use
the "SELECT" statement followed by the column
name.
Example
Select name and address from the "customers"
table, and display the return object:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT name, address FROM
customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Run example »
Save the code above in a file called
"demo_db_select2.js" and run the file:
Run "demo_db_select2.js"
C:\Users\Your Name>node demo_db_select2.js
Which will give you this result:
[
{ name: 'John', address: 'Highway 71'},
{ name: 'Peter', address: 'Lowstreet 4'},
{ name: 'Amy', address: 'Apple st 652'},
{ name: 'Hannah', address: 'Mountain 21'},
{ name: 'Michael', address: 'Valley 345'},
{ name: 'Sandy', address: 'Ocean blvd 2'},
{ name: 'Betty', address: 'Green Grass 1'},
{ name: 'Richard', address: 'Sky st 331'},
{ name: 'Susan', address: 'One way 98'},
{ name: 'Vicky', address: 'Yellow Garden 2'},
{ name: 'Ben', address: 'Park Lane 38'},
{ name: 'William', address: 'Central st 954'},
{ name: 'Chuck', address: 'Main Road 989'},
{ name: 'Viola', address: 'Sideway 1633'}
]
Include Modules
To include a module, use the require() function
with the name of the module:
var http = require('http');
Now your application has access to the HTTP
module, and is able to create a server:
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
Create Your Own Modules
You can create your own modules, and easily
include them in your applications.
The following example creates a module that
returns a date and time object:
ExampleGet your own Node.js Server
Create a module that returns the current date and
time:
exports.myDateTime = function () {
return Date();
};
Use the exports keyword to make properties and
methods available outside the module file.
Save the code above in a file called
"myfirstmodule.js"
Include Your Own Module
Now you can include and use the module in any of
your Node.js files.
Example
Use the module "myfirstmodule" in a Node.js file:
var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently:
" + dt.myDateTime());
res.end();
}).listen(8080);
Node.js as a Web Server
The HTTP module can create an HTTP server that
listens to server ports and gives a response back
to the client.
Use the createServer() method to create an HTTP
server:
ExampleGet your own Node.js Server
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to
the client
res.end(); //end the response
}).listen(8080); //the server object listens on port
8080
Add an HTTP Header
If the response from the HTTP server is supposed
to be displayed as HTML, you should include an
HTTP header with the correct content type:
Example
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-
Type': 'text/html'});
res.write('Hello World!');
res.end();
}).listen(8080);
Split the Query String
There are built-in modules to easily split the query
string into readable parts, such as the URL
module.
Example
Split the query string into readable parts:
var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query;
var txt = q.year + " " + q.month;
res.end(txt);
}).listen(8080);
Node.js as a File Server
The Node.js file system module allows you to
work with the file system on your computer.
To include the File System module, use
the require() method:
var fs = require('fs');
Common use for the File System module:
Read files
Create files
Update files
Delete files
Rename files
Read Files
The fs.readFile() method is used to read files on
your computer.
Assume we have the following HTML file (located
in the same folder as Node.js):
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and
return the content:
ExampleGet your own Node.js Server
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data)
{
res.writeHead(200, {'Content-
Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Run example »
Save the code above in a file called
"demo_readfile.js", and initiate the file:
Initiate demo_readfile.js:
C:\Users\Your Name>node demo_readfile.js
If you have followed the same steps on your
computer, you will see the same result as the
example: http://localhost:8080
Create Files
The File System module has methods for creating
new files:
fs.appendFile()
fs.open()
fs.writeFile()
The fs.appendFile() method appends specified
content to a file. If the file does not exist, the file
will be created:
Example
Create a new file using the appendFile() method:
var fs = require('fs');
fs.appendFile('mynewfile1.txt', 'Hello
content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Run example »
The fs.open() method takes a "flag" as the second
argument, if the flag is "w" for "writing", the
specified file is opened for writing. If the file does
not exist, an empty file is created:
Example
Create a new, empty file using the open() method:
var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {
if (err) throw err;
console.log('Saved!');
});
Run example »
The fs.writeFile() method replaces the specified
file and content if it exists. If the file does not
exist, a new file, containing the specified content,
will be created:
Example
Create a new file using the writeFile() method:
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'Hello
content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Run example »
Update Files
The File System module has methods for updating
files:
fs.appendFile()
fs.writeFile()
The fs.appendFile() method appends the specified
content at the end of the specified file:
Example
Append "This is my text." to the end of the file
"mynewfile1.txt":
var fs = require('fs');
fs.appendFile('mynewfile1.txt', ' This is my
text.', function (err) {
if (err) throw err;
console.log('Updated!');
});
Run example »
The fs.writeFile() method replaces the specified
file and content:
Example
Replace the content of the file "mynewfile3.txt":
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my
text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
Run example »
Delete Files
To delete a file with the File System module, use
the fs.unlink() method.
The fs.unlink() method deletes the specified file:
Example
Delete "mynewfile2.txt":
var fs = require('fs');
fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err;
console.log('File deleted!');
});
Run example »
Rename Files
To rename a file with the File System module, use
the fs.rename() method.
The fs.rename() method renames the specified
file:
Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', f
unction (err) {
if (err) throw err;
console.log('File Renamed!');
});
Run example »
The Built-in URL Module
The URL module splits up a web address into
readable parts.
To include the URL module, use
the require() method:
var url = require('url');
Parse an address with the url.parse() method, and
it will return a URL object with each part of the
address as properties:
ExampleGet your own Node.js Server
Split a web address into readable parts:
var url = require('url');
var adr = 'http://localhost:8080/default.htm?
year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?
year=2017&month=february'
var qdata = q.query; //returns an object: { year:
2017, month: 'february' }
console.log(qdata.month); //returns 'february'
Run example »
Node.js File Server
Now we know how to parse the query string, and
in the previous chapter we learned how to make
Node.js behave as a file server. Let us combine the
two, and serve the file requested by the client.
Create two html files and save them in the same
folder as your node.js files.
summer.html
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
winter.html
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>
Create a Node.js file that opens the requested file
and returns the content to the client. If anything
goes wrong, throw a 404 error:
demo_fileserver.js:
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-
Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-
Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
Remember to initiate the file:
Initiate demo_fileserver.js:
C:\Users\Your Name>node demo_fileserver.js
If you have followed the same steps on your
computer, you should see two different results
when opening these two addresses:
http://localhost:8080/summer.html
Will produce this result:
Summer
I love the sun!
http://localhost:8080/winter.html
Will produce this result:
Winter
I love the snow!
Events in Node.js
Every action on a computer is an event. Like when
a connection is made or a file is opened.
Objects in Node.js can fire events, like the
readStream object fires events when opening and
closing a file:
ExampleGet your own Node.js Server
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
console.log('The file is open');
});
Run example »
The EventEmitter Object
You can assign event handlers to your own events
with the EventEmitter object.
In the example below we have created a function
that will be executed when a "scream" event is
fired.
To fire an event, use the emit() method.
Example
var events = require('events');
var eventEmitter = new events.EventEmitter();
//Create an event handler:
var myEventHandler = function () {
console.log('I hear a scream!');
}
//Assign the event handler to an event:
eventEmitter.on('scream', myEventHandler);
//Fire the 'scream' event:
eventEmitter.emit('scream');
Run example »
Upload Files
Now you are ready to make a web page in Node.js
that lets the user upload files to your computer:
Step 1: Create an Upload Form
Create a Node.js file that writes an HTML form,
with an upload field:
ExampleGet your own Node.js Server
This code will produce an HTML form:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload"
method="post" enctype="multipart/form-
data">');
res.write('<input type="file"
name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}).listen(8080);
Step 2: Parse the Uploaded File
Include the Formidable module to be able to
parse the uploaded file once it reaches the server.
When the file is uploaded and parsed, it gets
placed on a temporary folder on your computer.
Example
The file will be uploaded, and placed on a
temporary folder:
var http = require('http');
var formidable = require('formidable');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.write('File uploaded');
res.end();
});
} else {
res.writeHead(200, {'Content-
Type': 'text/html'});
res.write('<form action="fileupload"
method="post" enctype="multipart/form-
data">');
res.write('<input type="file"
name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
Step 3: Save the File
When a file is successfully uploaded to the server,
it is placed on a temporary folder.
The path to this directory can be found in the
"files" object, passed as the third argument in
the parse() method's callback function.
To move the file to the folder of your choice, use
the File System module, and rename the file:
Example
Include the fs module, and move the file to the
current folder:
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.filepath;
var newpath = 'C:/Users/Your Name/' +
files.filetoupload.originalFilename;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-
Type': 'text/html'});
res.write('<form action="fileupload"
method="post" enctype="multipart/form-
data">');
res.write('<input type="file"
name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
Node.js Send an Email
❮ PreviousNext ❯
The Nodemailer Module
The Nodemailer module makes it easy to send
emails from your computer.
The Nodemailer module can be downloaded and
installed using npm:
C:\Users\Your Name>npm install nodemailer
After you have downloaded the Nodemailer
module, you can include the module in any
application:
var nodemailer = require('nodemailer');
Send an Email
Now you are ready to send emails from your
server.
Use the username and password from your
selected email provider to send an email. This
tutorial will show you how to use your Gmail
account to send an email:
ExampleGet your own Node.js Server
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'youremail@gmail.com',
pass: 'yourpassword'
}
});
var mailOptions = {
from: 'youremail@gmail.com',
to: 'myfriend@yahoo.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error,
info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
And that's it! Now your server is able to send
emails.
Multiple Receivers
To send an email to more than one receiver, add
them to the "to" property of the mailOptions
object, separated by commas:
Example
Send email to more than one address:
var mailOptions = {
from: 'youremail@gmail.com',
to: 'myfriend@yahoo.com, myotherfriend@yah
oo.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
}
Send HTML
To send HTML formatted text in your email, use
the "html" property instead of the "text" property:
Example
Send email containing HTML:
var mailOptions = {
from: 'youremail@gmail.com',
to: 'myfriend@yahoo.com',
subject: 'Sending Email using Node.js',
html: '<h1>Welcome</h1><p>That was easy!
</p>'
}