Exploring Node.js Core Libraries
Topic Outline (30-min)
Overview of Node.js Core Libraries:
Core libraries are built into Node.js and do not require installation via npm.
Key libraries include:
fs(File System): Manage file operations like reading, writing, and appending.http: Create and manage HTTP servers and handle requests.stream: Handle and manipulate streaming data like files or network responses.
Working with the
fsModule for File Operations:Read a file:
javascript코드 복사const fs = require('fs'); fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log('File content:', data); });Write to a file:
javascript코드 복사fs.writeFile('output.txt', 'Hello, Node.js!', (err) => { if (err) throw err; console.log('File written successfully'); });Append to a file:
javascript코드 복사fs.appendFile('output.txt', '\nAppended content', (err) => { if (err) throw err; console.log('Content appended successfully'); });
Introduction to the
httpModule for Creating Servers:Create a simple HTTP server:
javascript코드 복사const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, HTTP Server!'); }); server.listen(3000, () => { console.log('Server is running at http://localhost:3000'); });
Using Streams for Efficient Data Handling:
Streams allow handling large data piece by piece without loading the entire content into memory.
Example: Reading a file with a stream:
javascript코드 복사const fs = require('fs'); const readStream = fs.createReadStream('largeFile.txt', 'utf8'); readStream.on('data', (chunk) => { console.log('Received chunk:', chunk); });
Last updated