80.9k views
1 vote
How to import and export modules in node js

User L Balsdon
by
6.6k points

1 Answer

4 votes

Final answer:

In Node.js, use 'require' and 'module.exports' to import and export modules or 'import/export' syntax for ES6. The file path should be relative or just the module name if installed.

Step-by-step explanation:

To import and export modules in Node.js, you typically use the require function to import and the module.exports syntax to export. For example, to export a function or object from a module, you would include this in your module file:

module.exports = myFunction;

To import that module into another file, you would use:

const myFunction = require('./myModule');

In ES6, you can also use the import/export syntax. Exporting a function or variable:

export const myFunction = () => {};

Importing in another file:

import { myFunction } from './myModule';

Remember, the file path should be relative to the file you're working in unless it's an installed module, in which case you would just specify the module name.

User Linford
by
7.8k points