这种写法正确吗?
发布于 8 年前 作者 postgetme 4363 次浏览 来自 问答

想让一个模块,既可以被别的模块require,也可以单独在命令行下使用,是下面这种写法吗?

search.js 模块代码:

	function search(key) {
	}
	
	//方便在命令行下使用,是这种写法吗?
	if (process.argv[1] == __filename && process.argv[2]) {
		search(process.argv[2])
	}
	
	module.exports = search
3 回复

形式没问题,判断条件可以尽管成: require.main === module

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. 原文

回到顶部