"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Node.js Basics - Essential Things to Know

Node.js Basics - Essential Things to Know

Published on 2024-11-02
Browse:283

Node.js Basics - Essential Things to Know

Concept Highlights:

  1. Node.js Globals
  2. Node.js Modules
  3. The path Module
  4. The process Object
  5. Handling Input and Output
  6. File Management and Streams

1. Node.js Globals

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:

  • __dirname: The directory name of the current module.
  • __filename: The full path of the current file.
  • setTimeout(), clearTimeout(), setInterval(), clearInterval(): Functions for managing asynchronous timing.

e.g.)

console.log(__dirname); // outputs the current directory
console.log(__filename); // outputs the full path of the current file 

2. Node.js Modules

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:

  1. Core Modules: provided by Node.js like fs, http, and path.
  2. Third-Party Modules: installed via npm such as express or lodash.
  3. Custom Modules: created by you to organize your code.
const fs = require('fs'); // Require the built-in file system module

3. The path 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:

  • path.join() joins multiple path segments into one.
  • path.basename() returns the last part of a path (usually the file name).
  • paht.extname() returns the file extension.
const path = require('path');

const filePath = path.join(__dirname, 'folder', 'file.txt');
console.log(filePath); // Combines the paths to create a full file path

4. The process Object

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:

  • process.argv: arguments passed to the Node.js process.
  • process.env: environment variables.
  • process.exit(): terminates the process.
console.log(process.argv); // Returns an array of command-line arguments
console.log(process.env); // Accesses environment variables

5. Handling Input and Output

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}`);
});

6. File Management and Streams

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
Release Statement This article is reproduced at: https://dev.to/ryoichihomma/nodejs-basics-3lnm?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3