Including Functions from External Files in Node.js
If you want to utilize functions from a separate file, say "tools.js," in your main Node.js application ("app.js"), there are two options.
1. Basic Import:
You can directly require the "tools.js" file and select which functions to expose.
// tools.js module.exports = { foo: function () {}, bar: function () {} };
In "app.js":
const tools = require('./tools'); console.log(typeof tools.foo); // 'function' console.log(typeof tools.bar); // 'function'
This exposes only the specified functions from "tools.js." However, this method doesn't support exposing variables or classes.
2. Module Export:
You can turn "tools" into a module and then require it.
// tools.js export default { foo: function () {}, bar: function () {} }; export class Foo {}
In "app.js":
import tools from './tools'; console.log(typeof tools.foo); // 'function' console.log(typeof tools.bar); // 'function' console.log(tools.Foo instanceof Function); // true
This method supports importing all exports from the module, including variables and classes.
The above is the detailed content of How to Include Functions from External Files in Node.js?. For more information, please follow other related articles on the PHP Chinese website!