Incorporating External Functions in Node.js
In Node.js, it's often necessary to reuse functions defined in separate files. Let's illustrate how to achieve this functionality in detail.
Scenario:
Suppose you have an app.js file and a tools.js file containing functions. How can you access the functions from tools.js within app.js without creating a module?
Solution:
The Node.js require() function allows you to import external JavaScript files and access their contents. To accomplish your goal, follow these steps:
Define Functions in tools.js:
// tools.js module.exports = { foo: function () { // Function definition }, bar: function () { // Function definition } };
Notice that you must export the functions you want to make available in other files.
Require tools.js in app.js:
// app.js var tools = require('./tools'); console.log(typeof tools.foo); // 'function' console.log(typeof tools.bar); // 'function'
Additional Notes:
By following these steps, you can incorporate functions from external files into your Node.js applications, facilitating code organization and modularity.
The above is the detailed content of How Can I Reuse Functions from External Files in Node.js Without Using Modules?. For more information, please follow other related articles on the PHP Chinese website!