2

I would like to ask help in the following. Might be a duplicate but didnt found the solution. I have the following 2 files in 2 different path. A path: Root/AppleRoot/Apple.js B path: Root/PeachRoot/Peach.js

In Peach.js;

module.exports.harvest = harvest;
function harvest(input, callback){
}

In Apple.js i want to import harvest function from Peach.js

const harvestApple= require("../PeachRoot/Peach").harvest;

When i try to run the code it says the following:

Error:
Unable to import module

If i place the Peach.js in the same folder or below the AppleRoot and change the path i have no problems to import the module.

What am i missing? There must be a way to import modules from different directories

Researched topics: Link1 Link2 Link3 Link4 Link5

  • Unless Peach.js has nothing to do with the project why do you want to have it outside the project folder? – wattry Aug 08 '18 at 12:49
  • Imagine a big project where we have a centralized module place and have at least 7 lvl depth of directory structure. This has nothing to do real life project, but would be nice to be able to import modules from anywhere, if thats even possible in NodeJS – Szilágyi István Aug 08 '18 at 12:52
  • 1
    In that case I'd suggest you setup an external repo, like nexus, or pull your separate modules in from your choice of git repository. – wattry Aug 08 '18 at 12:57
  • I will consider it thanks :) – Szilágyi István Aug 08 '18 at 13:10

1 Answers1

2

If you want to use something in the project, Node.js has to be aware of it, so either use the full path directory in file or declare it in your package.json file:

{
 “name”: “harvestApp”,
 “dependencies”: {
   “Peach”: “file:/User/workspace/PeachRoot”,
   “Apple”: “file:/User/workspace/AppleRoot”,
 }
}
wattry
  • 936
  • 10
  • 22
  • 1
    Thanks! Nice one! – Szilágyi István Aug 08 '18 at 13:09
  • Hello, Where would this package.json file sit in the project, also do you use any kind of npm command with this? How would you include this in a json file ? – Szilágyi István Oct 11 '19 at 11:05
  • In this example, you would use `npm install /User/workspace/PeachRoot` you can provide either the relative path or the full path. Npm will resolve the relative path and put it in the package.json as a relative path. So it's probably easier to just include the path manually. When you run `npm install` after manually adding the path it will be installed anyway. – wattry Oct 11 '19 at 12:58