I have an npm module that requires a config file (provided by the user).
Is there a way to tell that module to look for a specific file in the user's directory ?
I want something like this:
In the module
const config = require(USER_ROOT_DIRECTORY + '/config.json');
In the user's project
/node_modules (contains the module file)
/src/index.js
/config.json
In the index.js file
const module = require('module'); // will automatically get the config.json file's content
You can use absolute path since you know with npm module requires what file simply add the path inside the module file better to add in index.js example-
var config = require('./subfolder/config.json')
Related
I am looking to access a JSON config file that the user would place next to their package.json from a node_module package that I created. Is there a best approach to do this. I tried a relative import but that didn't really work and I am not sure how best to accomplish dynamic imports if the config file doesn't exist because I want to allow it to not exist as well.
Here is how I tried to handle dynamic imports though:
export const overrides = (function () {
try {
return require('../../../../../../overrides.json');
} catch (_err) {
return null;
}
})();
Also I tried fs but I get a browser config error I am not sure if that is something else. I should research but I didn't understand the docs around that.
using a library
This worked for me: find-package-json
Basically on any js file who needs the base, home or workspace path, do this:
var finder = require('find-package-json');
var path = require('path');
var f = finder(__dirname);
var rootDirectory = path.dirname(f.next().filename);
rootDirectory will be the location of the folder in which the main package.json exist.
If you want to optimize, get the appRootPath variable at the start of your app and store/propagate the variable to the hole nodejs system.
no libraries
Without any library, this worked for me:
console.log("root directory: "+require('path').resolve('./'));
This will get you the root directory of your nodejs app no matter if you are using npm run start or node foo/bar/index.js
More ways to get the root directory here:
Determine project root from a running node.js application
usage
If you achieve to obtain the root directory of your nodejs app and your file is at the package.json level, use this variable like this to locate any file at root level:
rootDirectory+"/overrides.json"
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
This is the code for my app (index.js) . It uses a file named config.json using a relative path ./config.json. When I compile this into my mac using $pkg index.js, I obtain a test-macos file that is my app. Both the app and the config.json file are located in the same folder named project (this is why I can use the relative path ./config.json). However, once runnning the app I run into an error:
/Users/amelie/Documents/project/test-macos ;
exit; internal/fs/utils.js:312
throw err;
^ Error: ENOENT: no such file or directory, open './config.json'.
Therefore it seems that my app cannot find the config.json file. I could determine an absolute path but I need these two files to always be together because I need the path in the variable
var obj = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
to be always the same since I share those files to other people and the absolute path would therefore change. Is there a way to do this ?
As in the node documentation:
If there is no package.json file present in the directory, then
Node.js will attempt to load an index.js or index.node file out of
that directory. For example, if there was no package.json file in the
above example, then require('./some-library') would attempt to load:
./some-library/index.js
./some-library/index.node
So when we give the directory without the filename it looks automatically to index.js and index.node. Is there a way to look first for the name of the folder for the file? For instance:
I have a module in "Afolder/" directory, with the name Afolder.js and I use:
import module from 'Afolder';
Here what I want is that node automatically looks first for Afolder.js and then for index.js and index.node .
I'm writing a node module and need to read a file in the same directory as the file which requires my module.
For instance, I have app.js and in the same folder, template.html.
In some unknown directory is module.js and app.js requires it.
How can I read template.html from module.js?
Inside your file you will have a module global (not actually a global)
you can get the parent object using module.parent and the filename with module.parent.filename then you could extract the folder
so from from your module.js you can use module.parent.filename.
http://nodejs.org/api/modules.html
p = require('path')
template = p.join(p.dirname(module.parent.filename),'template.html')
And if you are looking for the path of the file which was executed then you can use require.main.filename
Have a look here: http://nodejs.org/docs/latest/api/globals.html#globals_dirname
The you can just do this from within app.js:
var path = __dirname + '/template.html';
Then you can send this path to your module.js via some function or API.
Then your module can just use this path.
Inside a "module.js", the trick is using module.parent.filename
I don't personally like using globals, and for certain files (like configuration or templates), managing module require stack isn't so hard.
module.parent is mapped to the parent requiring module (which could be app.js as in your example).
Combining module.parent.filename with the path module gets you a few useful things like:
var path = require('path');
var parent_path = path.dirname(module.parent.filename);
var parent_relative = path.resolve(path.join(parent_path, '../', 'view'));
var template = path.join(parent_path,'./views/template.html');
I don't like using globals for anything to do with paths, I get spagetti ../../../dir./s
I am new with Nodejs. I want to export from file1.js file to file2.js.
file1.js is located in root-directory and file2.js is in some sub-directory. When I am calling it as require('/file1') in file2.js its saying like Uncaught Error: Module name "/file1" has not been loaded yet for context: _. Use require([]). Any help? Sorry if this is silly, but I am new.
var Logger = require('./logger');
Requires the module you have written, in a file called logger.js stored in the same directory your code was launched from.(not necessarily the same directory your code is stored in).
var someOtherModule = require('../../someOtherModule');
Requires someOtherModule.js file two directories back from where the node process is launched.
var someOtherModule = require('./subDir/someOtherModule');
Requires someOtherModule.js file, sotred in subDir. subDir is a directory located at the level of where the node process was launched.
var awssum = require('awssum');
Requires a module installed via NPM, in the node_modules directory from which the process was launched, or any globally installed node modules. For versioning, the node_modules directory takes precedence.