Node.js - 內建模組
Hello, aspiring programmers! Today, we're going to embark on an exciting journey into the world of Node.js and its built-in modules. As your friendly neighborhood computer teacher, I'm thrilled to guide you through this adventure. Don't worry if you're new to programming – we'll start from the basics and work our way up. So, grab a cup of coffee (or your favorite beverage), and let's dive in!
What are Built-in Modules?
Before we start, let's understand what built-in modules are. Imagine you're moving into a new apartment. When you arrive, you find that the landlord has already installed some essential appliances like a refrigerator, stove, and washing machine. These are like built-in modules in Node.js – they're ready-to-use tools that come pre-installed with Node.js, saving you the trouble of creating them from scratch.
Why are Built-in Modules Important?
Built-in modules are the backbone of Node.js development. They provide essential functionalities that you'll use in almost every project. Learning these modules is like learning to use the basic tools in a toolbox – once you master them, you'll be ready to tackle a wide range of tasks!
Common Built-in Modules
Let's explore some of the most commonly used built-in modules in Node.js:
1. File System (fs) Module
The File System module is like having a personal assistant who can read, write, and manage files for you. Let's see it in action:
const fs = require('fs');
// Reading a file
fs.readFile('hello.txt', 'utf8', (err, data) => {
if (err) {
console.error('Oops! Error reading file:', err);
return;
}
console.log('File contents:', data);
});
// Writing to a file
fs.writeFile('goodbye.txt', 'Goodbye, World!', (err) => {
if (err) {
console.error('Oops! Error writing file:', err);
return;
}
console.log('File written successfully!');
});
In this example, we're first reading a file named 'hello.txt'. The readFile
function takes three arguments: the file name, the encoding (utf8 in this case), and a callback function that runs after the file is read. If there's an error, we log it; otherwise, we print the file contents.
Next, we're writing "Goodbye, World!" to a new file called 'goodbye.txt'. Again, we use a callback function to handle any potential errors or confirm success.
2. HTTP Module
The HTTP module is your ticket to creating web servers and making HTTP requests. It's like being the traffic controller of the internet! Let's create a simple web server:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World! Welcome to my server!');
});
server.listen(3000, 'localhost', () => {
console.log('Server running at http://localhost:3000/');
});
This code creates a server that listens on port 3000. When someone visits http://localhost:3000/, they'll see "Hello, World! Welcome to my server!". It's like setting up a lemonade stand on the internet!
3. Path Module
The Path module is your navigation system in the file system jungle. It helps you work with file and directory paths:
const path = require('path');
console.log(path.join('/home', 'user', 'documents', 'file.txt'));
// Output: /home/user/documents/file.txt
console.log(path.resolve('folder1', 'folder2', 'file.txt'));
// Output: /current/working/directory/folder1/folder2/file.txt
console.log(path.extname('myfile.txt'));
// Output: .txt
The join
method combines path segments, resolve
creates an absolute path, and extname
extracts the file extension. It's like having a GPS for your file system!
4. OS Module
The OS module gives you information about the operating system. It's like having x-ray vision for your computer:
const os = require('os');
console.log('CPU architecture:', os.arch());
console.log('Free memory:', os.freemem() / 1024 / 1024, 'MB');
console.log('Total memory:', os.totalmem() / 1024 / 1024, 'MB');
console.log('CPU cores:', os.cpus().length);
console.log('Home directory:', os.homedir());
This code will tell you about your system's CPU architecture, available memory, number of CPU cores, and your home directory. It's like getting a health check-up for your computer!
5. Events Module
The Events module is the heart of Node.js's event-driven architecture. It's like setting up a bunch of dominoes and watching them fall:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('An event occurred!');
});
myEmitter.emit('event');
Here, we create a custom event emitter, set up a listener for an 'event', and then emit that event. It's like yelling "Marco!" and waiting for someone to respond with "Polo!".
Conclusion
Congratulations! You've just taken your first steps into the world of Node.js built-in modules. These modules are powerful tools that will help you build amazing applications. Remember, learning to code is like learning a new language – it takes practice and patience. Don't be afraid to experiment and make mistakes. That's how we all learn!
As we wrap up, here's a table summarizing the modules we've covered:
Module | Description | Key Methods |
---|---|---|
fs | File System operations | readFile, writeFile |
http | Create web servers and make HTTP requests | createServer, listen |
path | Work with file and directory paths | join, resolve, extname |
os | Provides information about the operating system | arch, freemem, totalmem, cpus, homedir |
events | Handles and emits events | on, emit |
Keep exploring, keep coding, and most importantly, have fun! Remember, every expert was once a beginner. Who knows? The next big app might be written by you!
Credits: Image by storyset