Node.js Tutorial
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine, allowing JavaScript to run on the server side. It's widely used for building web servers, APIs, and real-time applications.
1. Installing Node.jsβ
- Download Node.js from the Node.js website.
- Run the installer and follow the instructions.
Verifying Installationβ
Check if Node.js and npm (Node Package Manager) are installed:
node -v
npm -v
2. Creating Your First Node.js Applicationβ
-
Create a new directory for your project:
mkdir my-node-app
cd my-node-app -
Initialize a new Node.js project:
npm init -yThis will create a
package.jsonfile to manage your projectβs dependencies. -
Create an
index.jsfile with the following code:console.log("Hello, Node.js!"); -
Run the application:
node index.js
3. Using Modules in Node.jsβ
Node.js has a modular structure, where different functionalities are separated into modules.
Importing Built-in Modulesβ
Example with the fs (File System) module:
const fs = require('fs');
fs.writeFile('hello.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File created!');
});
Creating Your Own Modulesβ
Create math.js:
exports.add = (a, b) => a + b;
exports.subtract = (a, b) => a - b;
In index.js, import and use the module:
const math = require('./math');
console.log(math.add(5, 3)); // 8
4. Installing and Using Packages with npmβ
Use npm to install third-party packages from the npm registry.
Example: Installing expressβ
-
Install the express package:
npm install express -
Create a basic Express server in
index.js:const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
}); -
Run the server:
node index.js
Open http://localhost:3000 in your browser.
5. Working with Async Code in Node.jsβ
Node.js is asynchronous and uses callbacks, promises, and async/await.
Example: Promisesβ
const fs = require('fs').promises;
fs.writeFile('example.txt', 'Hello, World!')
.then(() => console.log('File written'))
.catch((err) => console.error(err));
Example: Async/Awaitβ
async function writeFile() {
try {
await fs.writeFile('example.txt', 'Hello, Async/Await!');
console.log('File written');
} catch (err) {
console.error(err);
}
}
writeFile();
6. Building a Simple REST API with Expressβ
-
Define a REST API endpoint in
index.js:const express = require('express');
const app = express();
app.use(express.json());
let items = [{ id: 1, name: 'Item 1' }];
app.get('/items', (req, res) => {
res.json(items);
});
app.post('/items', (req, res) => {
const item = { id: items.length + 1, name: req.body.name };
items.push(item);
res.status(201).json(item);
});
app.listen(3000, () => console.log('Server running on http://localhost:3000')); -
Test the API with a tool like Postman or curl:
curl -X GET http://localhost:3000/items
7. Debugging in Node.jsβ
Use the Node.js debugger to debug applications.
Starting the Debuggerβ
Run Node.js with the inspect flag:
node inspect index.js
Set breakpoints and step through code using c (continue) and n (next).
Using console.log for Debuggingβ
Add console.log statements to inspect variables and function outputs.
8. Deploying Node.js Applicationsβ
Deploying with Herokuβ
-
Install the Heroku CLI and login.
-
Initialize a Git repository (if not already):
git init
git add .
git commit -m "Initial commit" -
Create a Heroku app and deploy:
heroku create
git push heroku master
Summaryβ
This tutorial covered the basics of Node.js:
- Setting up Node.js and creating a project.
- Working with modules and npm packages.
- Building a REST API with Express.
- Understanding async programming with Promises and async/await.
Node.js provides a powerful and scalable solution for building server-side applications using JavaScript.
Content Reviewβ
The content in this repository has been reviewed by chevp. Chevp is dedicated to ensuring that the information provided is accurate, relevant, and up-to-date, helping users to learn and implement programming skills effectively.
About the Reviewerβ
For more insights and contributions, visit chevp's GitHub profile: chevp's GitHub Profile.