这种写法正确吗?
想让一个模块,既可以被别的模块require,也可以单独在命令行下使用,是下面这种写法吗?
search.js 模块代码:
function search(key) {
}
//方便在命令行下使用,是这种写法吗?
if (process.argv[1] == __filename && process.argv[2]) {
search(process.argv[2])
}
module.exports = search
3 回复
Accessing the main module# When a file is run directly from Node.js, require.main is set to its module. That means that you can determine whether a file has been run directly by testing
require.main === module For a file foo.js, this will be true if run via node foo.js, but false if run by require(’./foo’).
Because module provides a filename property (normally equivalent to __filename), the entry point of the current application can be obtained by checking require.main.filename. 原文