Server-side JavaScript Runtime Environment
Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser. It allows developers to use JavaScript to write command line tools and for server-side scripting.
To install Node.js, visit the official website (nodejs.org) and download the installer for your operating system. Follow the installation instructions provided.
Create a file named app.js with the following content:
console.log('Hello, World!');
Run the script using the command: node app.js
Node.js comes with several built-in modules. Here's an example using the fs (File System) module:
const fs = require('fs');
fs.writeFile('example.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File has been saved!');
});
Node.js can be used to create a simple web server:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000/');
});
NPM is the package manager for Node.js. It allows you to install and manage third-party packages. Here's how to initialize a new Node.js project:
npm init
To install a package:
npm install package-name
Node.js is designed to be non-blocking and asynchronous. Here's an example using Promises:
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (error) {
console.error('Error reading file:', error);
}
}
readFile();
Node.js uses an event-driven programming model. Here's an example:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('An event occurred!');
});
myEmitter.emit('event');
These examples demonstrate some of the core concepts and features of Node.js. As you continue to explore Node.js, you'll discover its vast ecosystem and powerful capabilities for building scalable, high-performance applications.