Today, I started learning Node.js, and I’m excited to share the basics I explored—like creating a server, using built-in modules, and understanding how Node.js works under the hood.
What is Node.js?
Node.js is a runtime environment that allows you to run JavaScript on the server-side. It's built on the Chrome V8 JavaScript engine, which makes it fast and efficient.
Creating a Simple Server
const http = require('http');
const server = http.createServer((req, res) => {
res.write('Hello World!');
res.end();
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
This code sets up a basic web server that listens on port 3000.
Sending a Request
You can test this using your browser or a tool like curl:
Importing Node.js Core Modules
Here are some useful built-in modules:
const fs = require('fs'); // File system
const path = require('path'); // File path handling
const os = require('os'); // OS info
const https = require('https'); // HTTPS requests
Example: Reading a file using fs
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
Synchronous vs Asynchronous
Synchronous code blocks execution:
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data); // waits for the file to be read
Asynchronous code doesn't block:
fs.readFile('example.txt', 'utf8', (err, data) => {
console.log(data); // executed later
});
Callbacks
Callback example:
function greet(name, callback) {
console.log('Hello, ' + name);
callback();
}
greet('Alice', () => {
console.log('Callback executed');
});
Streams (Reading/Writing Data in Chunks)
const readStream = fs.createReadStream('largefile.txt', 'utf8');
readStream.on('data', chunk => {
console.log('Chunk received:', chunk);
});
Streams help with performance when handling large files.
Summary of Concepts I Learned
Node.js runs JavaScript outside the browser
Created a server with the http module
Imported built-in modules: fs, path, os, https
Understood sync vs async
Explored callbacks, promises, and async/await
Learned about the event loop and single-threaded architecture
Used streams for handling large data
What’s Next?
Next, I plan to learn:
Express.js (web framework)
Building REST APIs
Handling JSON and databases (like MongoDB)
Top comments (0)