In this tutorial, we will cover the basics of Node.js and demonstrate a live session for beginners. Node.js is an open-source, cross-platform JavaScript runtime environment that allows you to run JavaScript code outside of a web browser. It is commonly used for building server-side applications and APIs.
Before we get started, make sure you have Node.js installed on your computer. You can download the latest version of Node.js from the official website. Once Node.js is installed, you can check the version by running the following command in your terminal:
node -v
Now, let’s start by creating a new Node.js project. Create a new directory for your project and navigate to it in your terminal:
mkdir nodejs-tutorial
cd nodejs-tutorial
Next, create a new file called app.js
in your project directory. This will be our main Node.js file where we will write our code. Open app.js
in your text editor and let’s get started!
First, let’s create a simple HTTP server using Node.js. Copy and paste the following code into app.js
:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!n');
});
server.listen(3000, 'localhost', () => {
console.log('Server running at http://localhost:3000/');
});
This code creates a basic HTTP server that listens on port 3000 and responds with "Hello, World!" when you visit http://localhost:3000/
in your browser. To run the server, use the following command:
node app.js
Visit http://localhost:3000/
in your browser to see the "Hello, World!" message displayed.
Next, let’s look at how to work with modules in Node.js. Node.js uses CommonJS modules to organize code into reusable units. Let’s create a new module called greet.js
that exports a function to say hello:
Create a new file called greet.js
in your project directory and paste the following code:
module.exports = function(name) {
return `Hello, ${name}!`;
};
Now, let’s use the greet.js
module in our app.js
file. Update app.js
to include the following code:
const greet = require('./greet');
console.log(greet('World'));
This code imports the greet
module and uses it to say hello to the world. Run the app.js
file using the node
command to see the output.
This is just a basic introduction to Node.js for beginners. There is so much more to learn and explore, including working with databases, building APIs, and deploying applications. I encourage you to continue learning and experimenting with Node.js to see what you can build.
I hope this tutorial was helpful in getting you started with Node.js. Happy coding!