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
Mary-Kate OlsenOriginal
2024-11-30 01:40:10772browse

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

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!

Statement:
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