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);
To import functions from an external file, such as "tools.js," follow these steps:
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 } };
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
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!