Here’s a 20-minute tutorial to help you get started with Node.js, a powerful runtime environment that allows you to run JavaScript outside of a browser, typically for server-side applications. This tutorial assumes you know basic JavaScript, but not Node.js.
1. What is Node.js? (2 minutes)¶
- Node.js is a JavaScript runtime built on Chrome's V8 engine that allows you to run JavaScript on the server.
- Node.js is event-driven, non-blocking, and uses asynchronous programming, making it ideal for building scalable network applications.
- npm (Node Package Manager) comes with Node.js and is used to install external packages and libraries.
2. Setting Up Node.js (3 minutes)¶
Step 1: Install Node.js¶
- Download and install Node.js from nodejs.org. Choose the LTS version for stability.
- After installation, check if Node.js and npm are installed:
bash node -v # Check Node.js version npm -v # Check npm version
Step 2: Create a Project Directory¶
- Create a new folder for your project:
bash mkdir my-node-app cd my-node-app
Step 3: Initialize a Node.js Project¶
- Run the following command to create a
package.jsonfile (which manages project dependencies):bash npm init -yThis will generate apackage.jsonfile with default values.
3. Writing Your First Node.js Script (3 minutes)¶
Step 1: Create a JavaScript File¶
- Create a new file
app.jsinside your project folder.
Step 2: Write a Simple Script¶
- Add the following code to
app.js:js console.log('Hello, Node.js!');
Step 3: Run the Script¶
- Run the script using Node.js:
bash node app.jsYou should seeHello, Node.js!printed in the terminal.
4. Node.js Modules (3 minutes)¶
Node.js has a module system that allows you to split your code into multiple files and reuse code across your application.
Built-in Modules¶
Node.js comes with several built-in modules like fs (file system), http, path, and os.
Example: File System (fs) Module¶
- Update
app.jsto include thefsmodule and read a file: ```js const fs = require('fs');
fs.readFile('message.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
``
- Create a filemessage.txtwith some text content.
- Run the script again withnode app.js` to see the file's content.
Creating Your Own Module¶
- Create a new file
greet.js:``js function greet(name) { returnHello, ${name}!`; }
module.exports = greet; ```
- Now import this module in
app.jsand use it:js const greet = require('./greet'); console.log(greet('John')); // Outputs: Hello, John!
5. Creating a Simple HTTP Server (3 minutes)¶
Node.js is commonly used to create web servers. Let’s create a basic HTTP server using the built-in http module.
Step 1: Use the http Module¶
- Replace the content of
app.jswith the following code to create a basic server: ```js const http = require('http');
const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); });
server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); }); ```
Step 2: Run the Server¶
- Start the server by running:
bash node app.js - Visit
http://localhost:3000/in your browser. You should see Hello, World! displayed on the page.
6. Asynchronous Programming and Callbacks (3 minutes)¶
Node.js uses non-blocking I/O and callbacks to handle asynchronous tasks.
Example: Asynchronous File Read¶
const fs = require('fs');
console.log('Start reading file...');
fs.readFile('message.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log('Finished reading file');
- Output:
Start reading file... Finished reading file (file contents)This shows that Node.js doesn’t wait for the file read to complete before executing the next line of code.
7. npm and Installing External Packages (2 minutes)¶
Node.js comes with npm, which lets you install and manage external libraries and packages.
Step 1: Install a Package¶
- Let’s install the Express framework (a web framework for Node.js):
bash npm install express
Step 2: Use the Installed Package¶
- Create a simple Express server: ```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 with
node app.jsand visithttp://localhost:3000/to see Hello from Express!.
8. Working with JSON and APIs (2 minutes)¶
Node.js is great for building APIs that serve JSON data.
Example: Sending JSON Response¶
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Hello, JSON!' }));
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
- Visit
http://localhost:3000/and you’ll see the JSON response:{"message":"Hello, JSON!"}.
9. Error Handling (2 minutes)¶
Handling errors properly is important in Node.js.
Example: Error Handling in File Read¶
const fs = require('fs');
fs.readFile('non-existent-file.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log(data);
});
- If the file doesn’t exist, it will print an error message instead of crashing the program.
10. Final Tips (1 minute)¶
- Event Loop: Node.js uses an event-driven, non-blocking I/O model, making it highly efficient for handling many connections simultaneously.
- Asynchronous Programming: Learn about promises and async/await for handling asynchronous tasks in a cleaner way.
- Node.js Documentation: Refer to the Node.js documentation for in-depth exploration of Node’s features and APIs.
With this basic understanding, you’re ready to start building simple server-side applications using Node.js!