Ticker

6/recent/ticker-posts

Node.js Basics

Node.js Basics

Introduction to Node.js:
Node.js is an open-source, cross-platform runtime environment that allows developers to execute JavaScript code outside the browser. It is built on Chrome's V8 JavaScript engine, providing high performance and scalability.

Installing Node.js:
To install Node.js, visit the official Node.js website (https://nodejs.org) and download the appropriate version for your operating system. Once downloaded, follow the installation instructions for your specific OS.

Creating a Simple Node.js Application:
Create a new file named app.js and open it in your favorite text editor. In this file, we'll write a simple "Hello, Node.js!" program.

javascript
// app.js
console.log("Hello, Node.js!");

Running the Node.js Application:
To execute the Node.js application, open your terminal or command prompt, navigate to the directory where app.js is located, and type the following command:


node app.js

You should see the output "Hello, Node.js!" displayed in the terminal.

Modules in Node.js:
Node.js provides a module system that allows developers to organize code into reusable components. Let's create a simple module in a new file named greet.js.

javascript
// greet.js
function sayHello(name) {
return "Hello, " + name + "!";
}

module.exports = sayHello;

Now, let's use the greet.js module in our app.js file:

javascript
// app.js
const greet = require('./greet');

console.log(greet("Alice")); // Output: "Hello, Alice!"
console.log(greet("Bob")); // Output: "Hello, Bob!"

Asynchronous Programming:
Node.js is known for its asynchronous capabilities, allowing non-blocking I/O operations. One common asynchronous function is setTimeout().

javascript
// app.js
console.log("Start");

setTimeout(() => {
console.log("Inside the setTimeout callback");
}, 2000);

console.log("End");

When executed, this code will log "Start," then "End," and after a 2-second delay, it will log "Inside the setTimeout callback."

Conclusion:
This documentation provided a brief overview of Node.js basics, including installation, creating a simple Node.js application, working with modules, and understanding asynchronous programming. With this knowledge, you can start building powerful and scalable applications using Node.js.

Post a Comment

0 Comments