I am building a tool which is basically a node.js module. This tool can be installed globally (with -g
option) I have few static files in the module to generate a report. If the module is invoked locally, I can refer to the static files with relative path ./node_modules/<module>/static/filename
. But when the tool is invoked as a command, how do I refer to the static files? And how can I determine whether the tool is invoked as a local module or as a command?
相关问题
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- google-drive can't get push notifications
- Failed at the electron@1.8.2 postinstall script
- How to reimport module with ES6 import
- Webpack getting started, import error
相关文章
- node连接远程oracle报错
- How can make folder with Firebase Cloud Functions
- @angular-cli install fails with deprecated request
- node.js modify file data stream?
- How to resolve hostname to an ip address in node j
- Transactionally writing files in Node.js
- Log to node console or debug during webpack build
- Get file created date in node
When your tool is installed globally, there are usually two entries on Unix systems:
/usr/local/lib/node_modules/<module>/
-> the directory containing all module source files/usr/local/bin/<script.js>
-> symlink to your module executable scriptBecause Node is using the real path (i.e. after all symlinks were resolved) to resolve a path relative to current module, you don't need to worry about differences between global and local install.
What you do need to handle is the possibly different current working directory where the node process is running. The solution is to resolve the relative path to your static file against the absolute path where your module resides, not to assume that the node process will run in a particular directory as you do in your example.
There are two ways for that:
Using
__dirname
(API docs), which contains the directory name (path) of the current source file:Using
require.resolve()
, which returns the exact same filename as would be used by a call torequire()
:Use the magic variable __dirname. It refers to the directory containing your script file.
http://nodejs.org/api/globals.html#globals_dirname