Node.js comes with several global objects and functions that are available anywhere in an application without needing to require() them. Some of the key global objects include:
e.g.)
console.log(__dirname); // outputs the current directory console.log(__filename); // outputs the full path of the current file
Node.js follows a modular structure, where code is divided into smaller, reusable modules. You can load built-in or custom modules using the require() function.
e.g.) There are three types of modules in Node.js:
const fs = require('fs'); // Require the built-in file system module
The path module in Node.js provides utilities for working with file and directory paths. It's especially useful for making your code platform-independent since path separators ( on Windows) can vary between operating systems.
e.g.) Key methods in the path module:
const path = require('path'); const filePath = path.join(__dirname, 'folder', 'file.txt'); console.log(filePath); // Combines the paths to create a full file path
The process object in Node.js provides information about and control over the current Node.js process. It is a global object that allows you to internet with the runtime environment.
e.g.) Some useful properties and methods of process include:
console.log(process.argv); // Returns an array of command-line arguments console.log(process.env); // Accesses environment variables
Node.js provides simple ways to handle input and output, particularly through its process object for working with standard input and output.
e.g.) This example listens for user input and logs it to the console. For more advanced I/O handling, you can also use streams, which allow you to process data piece by piece instead of loading the entire I/O into memory at once.
process.stdin.on('data', (data) => { console.log(`You typed: ${data}`); });
File management is a critical part of many Node.js applications, and Node's fs (file system) module provides a range of methods to work with the file system. You can read, write, and manage files using the asynchronous or synchronous APIs.
e.g.)
const fs = require('fs'); // Asynchronous file reading fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); // Writing to a file fs.writeFile('output.txt', 'This is some content', (err) => { if (err) throw err; console.log('File written successfully'); });
Node.js also has a powerful system for working with streams, which are used to handle large amounts of data efficiently. Streams are often used for reading/writing files or handling network communication.
const fs = require('fs'); const readStream = fs.createReadStream('example.txt'); const writeStream = fs.createWriteStream('output.txt'); readStream.pipe(writeStream); // Piping data from one file to another
The above is the detailed content of Node.js Basics - Essential Things to Know. For more information, please follow other related articles on the PHP Chinese website!