Node.js is a powerful JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript outside of a browser, enabling you to build scalable network applications. This tutorial will guide you through the basics of Node.js.
Getting Started
Before you begin, make sure you have Node.js installed on your machine. You can download and install it from the official Node.js website.
Basic Structure
A typical Node.js application consists of the following files:
package.json
: This file contains metadata about the application and its dependencies.index.js
orapp.js
: This is the main entry point of the application.
Here's an example of a simple "Hello, World!" application:
// index.js
console.log('Hello, World!');
Modules
Node.js uses modules to organize your code. You can create your own modules or use existing ones. To use a module, you need to require it in your application.
For example, to use the http
module, you would do the following:
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
}).listen(3000);
console.log('Server running on port 3000');
NPM
NPM (Node Package Manager) is a package manager for Node.js. It allows you to install and manage packages for your application.
To install a package, use the following command:
npm install <package-name>
For example, to install the express
framework, you would do the following:
npm install express
Practice
Now that you have a basic understanding of Node.js, it's time to practice. Try creating a simple web server using the http
module and serve static files from the public
directory.
Remember, the best way to learn is by doing. Happy coding!