Using a module in the external class itself without creating an instance in Node.js

CK CK 3788 
Created at  
349 0 0

You can use a module within an external class in Node.js without creating an instance of that class by using static methods. Static methods are called on the class itself rather than on instances of the class.

 

Here's how you can do it:

Step 1: Create the Custom Class with Static Methods

File: MyClass.js

// Import any modules you need
const fs = require('fs');

class MyClass {
  static greet(name) {
    return `Hello, ${name}!`;
  }

  static readFile(filePath) {
    try {
      const data = fs.readFileSync(filePath, 'utf8');
      return data;
    } catch (err) {
      console.error('Error reading file:', err);
      return null;
    }
  }
}

// Export the class so it can be imported elsewhere
module.exports = MyClass;

 

Step 2: Import and Use the Static Methods without Creating an Instance

File: app.js

// Import the custom class
const MyClass = require('./MyClass');

// Use the static methods without creating an instance
console.log(MyClass.greet('John Doe')); // Output: Hello, John Doe!

const fileContent = MyClass.readFile('example.txt');
if (fileContent) {
  console.log('File content:', fileContent);
} else {
  console.log('Failed to read the file.');
}

Explanation

  • Static Methods: These are methods defined with the static keyword. They belong to the class itself and can be called without creating an instance of the class.
  • Modules within the Class: You can import any necessary modules (like fs in this example) and use them within the static methods of your class.
  • No Instance Creation: Since the methods are static, you don't need to create an instance of MyClass to use them. You can directly call MyClass.greet() or MyClass.readFile().

 

Step 3: Run the Application

To see it in action, run the app.js file using Node.js:

node app.js

This setup allows you to use the functionalities provided by the class without needing to create instances, which can be useful for utility functions or scenarios where instance state is not required.

Tags Class static method Facebook X
Comments 0
Similar posts
  1. A simple Javascript class example with static method for Node.js
    660
  1. Get client IP address and user agent in Node.js
    1,527
  2. forEach method in JavaScript when working with arrays
    663
  3. CRC32B function code in Javascript
    1,834
  4. Node.js-based Web Server supporting multiple path
    596
  5. A simple Javascript class example with static method for Node.js
    660
  6. Setting a Common Path for require() in Node.js
    992
  7. Import all JS files in a specific folder for Node.js programming
    1,720
  8. A simple example to access a PostgreSQL database in Node.js
    1,100
  9. Node.js code example to access Google BigQuery
    1,179
  10. Investigation on package.js for Node.js source code
    817
  11. Using MySQL in Node.js
    474
  12. A Node.js script that checks if a module is installed before requiring it
    767
  13. Worker Threads and Mutual Exclusion in Node.js
    457
  14. Node.js external modules
    425
  15. Multi-threaded Web Server based in Node.js
    860
  16. A basic HTTP server based in Node.js
    535
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,704
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    197
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    508
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    221
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    575
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    252
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    326
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252