Home > Web Front-end > JS Tutorial > How Can I Import and Use Functions from External Files in Node.js?

How Can I Import and Use Functions from External Files in Node.js?

Susan Sarandon
Release: 2024-11-25 05:38:14
Original
886 people have browsed it

How Can I Import and Use Functions from External Files in Node.js?

Importing Functions from External Files in Node.js

In Node.js, it is possible to reuse code across multiple files by importing functions from one file into another. This approach allows for modular code organization and eliminates duplication.

Importing Functions from a Simple File

Let's consider the following scenario:

// app.js
var express = require('express');
var app = express.createServer();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res){
  res.render('index', {locals: {
    title: 'NowJS + Express Example'
  }});
});

app.listen(8080);
Copy after login

To import functions from an external file, such as "tools.js," follow these steps:

  1. Create an External File: Save the functions you want to import in a separate file, e.g., "tools.js."
  2. Export Functions: In the external file, wrap the functions you want to make available in a module.exports object:

    // tools.js
    module.exports = {
      foo: function () {
     // function implementation
      },
      bar: function () {
     // function implementation
      }
    };
    Copy after login
  3. Import Functions in Main File: In your main file (e.g., app.js), use the require() function to import the external file and access its exported functions:

    // app.js
    var tools = require('./tools');
    console.log(typeof tools.foo); // returns 'function'
    
    // You can now use the imported functions within your code
    Copy after login

By following these steps, you can effectively import functions from other files in Node.js, facilitating code reusability and modularity.

The above is the detailed content of How Can I Import and Use Functions from External Files in Node.js?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template