This tutorial aims to introduce you to Node.js, an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside of a web browser.
By the end of this tutorial, you will:
- Understand what Node.js is and how it works
- Know how to install and set up Node.js on your computer
- Understand how to write and run a simple Node.js script
Before we begin, you should have a basic understanding of JavaScript.
Node.js is a JavaScript runtime, built on Chrome's V8 JavaScript engine. It's used to build scalable network applications and to execute JavaScript code server-side. This means you can write JavaScript code just like you do for the browser, but it runs on your server.
To verify that Node.js is installed, open your terminal or command prompt and type:
node -v
You should see the version of Node.js that you installed.
Create a new file called app.js
and open it in your text editor. Write the following code:
console.log('Hello, Node.js!');
Save the file, go back to your terminal, navigate to the folder where you saved your app.js
file and type:
node app.js
You should see Hello, Node.js!
logged in your terminal.
Let's create a simple HTTP server using Node.js. We'll use the built-in http
module.
// Load HTTP module
const http = require('http');
// Create HTTP server and listen on port 8000 for requests
const server = http.createServer((request, response) => {
// Set the response HTTP header with HTTP status and Content type
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body "Hello World"
response.end('Hello World\n');
});
server.listen(8000);
// Print URL for accessing server
console.log('Server running at http://127.0.0.1:8000/');
When you run this script with node app.js
, you should see Server running at http://127.0.0.1:8000/
in your terminal. If you visit that URL in your web browser, you'll see a page that says Hello World
.
In this tutorial, you've learned what Node.js is, how to install it, and how to write a basic script. You've also learned how to create a simple HTTP server using Node.js.
To continue learning, you might want to explore more about the Node.js documentation. This will introduce you to more advanced topics, like event-driven programming, streams and buffers, and the file system API.
Remember, Node.js is all about practice. The more you use it, the more comfortable you'll become. Good luck!