Home > Web Front-end > JS Tutorial > How to Include Functions from External Files in Node.js?

How to Include Functions from External Files in Node.js?

Mary-Kate Olsen
Release: 2024-11-30 01:40:10
Original
760 people have browsed it

How to Include Functions from External Files in Node.js?

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 () {}
};
Copy after login

In "app.js":

const tools = require('./tools');
console.log(typeof tools.foo); // 'function'
console.log(typeof tools.bar); // 'function'
Copy after login

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 {}
Copy after login

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
Copy after login

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!

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