Monday, 5 June 2017

Custom npm module. How to get current node.js project path after module installation

Hello im currently learning node.js and want to make custom npm module (lets name it "mymodule"), this module should work that way: After "npm install", "mymodule" should check if file with name "mymodule.config.js" exist in project root directory, if file exist then I want to read data from it, if file is not exist then I want to create it. Also i want to know if file has been changed (I will try to use chokidar for that task https://github.com/paulmillr/chokidar).

My problem is that I dont know how to get project directory.

Currently I figure out how to get module directory, so if module installed localy i could get project path from it, or just use something like this "../../", but maybe there is a better way to do that ? And what if module instaled globaly, how to get project path then ?

mymodule/package.json

{
  "name": "mymodule",
  "version": "1.0.0",
  "description": "My custom module",
  "main": "mymodule.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "install": "node ./scriptsInstall.js"
  }
}

mymodule/scriptsInstall.js

var path = require('path');
var moduleDir = path.dirname(require.main.filename);


// moduleDir - module directory



via user1093555

No comments:

Post a Comment