Creating applications with Node.js¶
Using Node.js to create command-line applications¶
Node.js can be used to create command-line applications that can be run from the terminal or command prompt. These applications can perform various tasks, such as file manipulation, data processing, or system administration.
To create a command-line application in Node.js, you can use the process.argv
object to access the command-line arguments passed to the application. Here's an example of a simple command-line application that takes two numbers as arguments and adds them together:
const args = process.argv.slice(2);
const num1 = parseInt(args[0]);
const num2 = parseInt(args[1]);
const sum = num1 + num2;
console.log(sum);
In this example, we're using the process.argv
object to retrieve the command-line arguments passed to the application. We then convert the arguments to numbers using parseInt()
and add them together. Finally, we use console.log()
to output the result to the terminal.
Creating a basic web server with Node.js¶
Node.js can also be used to create web applications and servers. To create a basic web server in Node.js, you can use the built-in http
module. Here's an example of a simple web server that responds to HTTP requests with the text "Hello, world!":
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, world!');
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example, we're using the http.createServer()
method to create a new web server. We define a callback function that is called every time the server receives an HTTP request. Inside the callback function, we set the response headers using res.writeHead()
and write the response body using res.end()
. Finally, we start the server listening on port 3000 using server.listen()
.
Handling HTTP requests and responses¶
When an HTTP request is received by a Node.js server, it is passed to the server's request listener function as an argument. The request object contains information about the incoming request, such as the request method, URL, headers, and body.
Similarly, when an HTTP response is sent from a Node.js server, it is passed to the server's response listener function as an argument. The response object contains methods for setting the response headers and writing the response body.
Using Node.js's http
library to create a web server¶
Node.js's built-in http
library provides a range of methods and classes for creating web servers and handling HTTP requests and responses. Some of the key classes and methods in the http
library include:
http.createServer()
: Creates a new HTTP server.http.Server
: Represents an HTTP server.http.IncomingMessage
: Represents an incoming HTTP request.http.ServerResponse
: Represents an outgoing HTTP response.req.method
: The HTTP method used in the request (e.g. GET, POST).req.url
: The URL of the requested resource.req.headers
: An object containing the headers of the request.res.writeHead()
: Sets the HTTP response headers.res.write()
: Writes data to the response body.res.end()
: Ends the response and sends it to the client.
By using these classes and methods, you can create powerful and flexible web applications with Node.js.
A basic app using http
library¶
The following code will create a web server that responds with "Hello, World!":
- Start by setting up a new Node.js project with the following structure:
├── server.js
└── public
└── index.html
-
Open the
index.html
file in thepublic
folder and add the following content:<!DOCTYPE html> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello, World!</h1> </body> </html>
-
In the
server.js
file, add the following code to create a basic web server using the built-inhttp
module:
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// Set the content type to HTML
res.setHeader('Content-Type', 'text/html');
// Read the index.html file and send its contents as the response
const filePath = path.join(__dirname, 'public', 'index.html');
fs.readFile(filePath, 'utf-8', (err, content) => {
if (err) {
res.statusCode = 500;
res.end('Internal Server Error');
console.error(err);
} else {
res.statusCode = 200;
res.end(content);
}
});
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
-
Open a terminal, navigate to the project folder, and run the following command to start the server:
node server.js
-
Open a web browser and visit
http://localhost:3000
to see the "Hello, World!" message displayed in HTML.
Using a template engine¶
A template engine is a library that allows you to generate dynamic content by combining predefined templates with data. It simplifies the process of creating dynamic web pages or generating other text-based documents by separating the presentation logic (the template) from the data or business logic.
In the context of Node.js, there are several popular template engines available that can be used to generate dynamic HTML pages, such as:
- EJS (Embedded JavaScript): EJS is a simple and widely used template engine for Node.js. It allows you to embed JavaScript code within your HTML templates. You can define variables, loops, conditionals, and other JavaScript expressions directly in the template. EJS templates use the
.ejs
file extension.
Example usage:
<!-- index.ejs -->
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Page</title>
</head>
<body>
<h1>Hello, <%= name %>!</h1>
<% if (isAdmin) { %>
<p>Welcome, administrator!</p>
<% } else { %>
<p>Welcome, guest!</p>
<% } %>
</body>
</html>
- Pug (formerly Jade): Pug is a concise and feature-rich template engine for Node.js. It uses indentation and a clean syntax to define HTML structure and elements. Pug templates use the
.pug
file extension.
Example usage:
// index.pug
doctype html
html
head
title= pageTitle
body
h1= greeting
if isAdmin
p Welcome, administrator!
else
p Welcome, guest!
- nunjucks: Nunjucks is another popular template engine for Node.js that provides a powerful and flexible way to generate dynamic content. It is inspired by Jinja2, a template engine used in Python.
Example usage:
<!-- index.nkj -->
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Page</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
{% if isAdmin %}
<p>Welcome, administrator!</p>
{% else %}
<p>Welcome, guest!</p>
{% endif %}
</body>
</html>
These are just a few examples of popular template engines in the Node.js ecosystem. Each template engine has its own syntax and features, but they all serve the purpose of separating the presentation logic from the data, making it easier to generate dynamic content in web applications.
By using a template engine, you can dynamically render HTML pages with data from your Node.js application, resulting in more maintainable and flexible code.
Basic example using EJS
¶
Here's an example of using EJS as a template engine in a Node.js application:
-
Set up a new Node.js project with the following structure:
├── server.js └── views └── index.ejs
-
In the
views
folder, create anindex.ejs
file with the following content:<!DOCTYPE html> <html> <head> <title>Dynamic Page</title> </head> <body> <h1>Hello, <%= name %>!</h1> <% if (isAdmin) { %> <p>Welcome, administrator!</p> <% } else { %> <p>Welcome, guest!</p> <% } %> </body> </html>
-
In your
server.js
file, include the necessary code to set up a basic HTTP server and render the EJS template:const http = require('http'); const fs = require('fs'); const ejs = require('ejs'); const server = http.createServer((req, res) => { // Read the template file fs.readFile('./views/index.ejs', 'utf8', (err, template) => { if (err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Internal Server Error'); return; } // Define the data const data = { name: 'John Doe', isAdmin: true }; // Render the template with the data const rendered = ejs.render(template, data); // Set the response headers and send the rendered template res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(rendered); }); }); const port = 3000; // Start the server server.listen(port, () => { console.log(`Server running on port ${port}`); });
-
Run the server using the command:
node server.js
-
Open a web browser and visit
http://localhost:3000
to see the rendered EJS template with the dynamic content.
In this example, the HTTP server is created using the http
module. The fs
module is used to read the EJS template file, and the ejs
module is used to render the template with the provided data.
By dynamically rendering the EJS template, you can generate HTML pages with dynamic content.
You have more information about EJS in Embedded JavaScript templating