Search code examples
node.jsrequire

NodeJs require, custom module, path,


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


Solution

  • 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”,
     }
    }