简体   繁体   中英

How to import a module in Node js

I have two js files: MyBreakdown.js and MyService.js and I want to import the second one into the first one.

There are in different subfolders of the same directory, like this:

server/reports/plan/MyService.js 

and

serer/validation/rules/sections/MyBreakdown.js

So what I've tried in MyBreakdown.js file is to import MyService.js in two ways but none of them worked:

  1. const seasonalityService = require('server/reports/plan/myService');
  2. const seasonalityService = require('../../../../myService');

Does anyone know how to solve this? Thanks

Module imports in NodeJS are done by filenames . For instance:

const seasonalityService = require('../../../../reports/plan/MyService');

Lets say you are inside - serer/validation/rules/sections/MyBreakdown.js

Use path.join to form the right path.

var path = require('path');

var filepath = path.join(__dirname, '../../../../', '/reports/plan/MyService');

console.log(filepath);

var serviceFile = require(filepath);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM