如何从节点模块中加载用户特定的文件?
我正在创build一个应用程序可以导入的节点模块(通过npm install)。 我的模块中的函数将接受在用户的应用程序中设置的.json文件的位置(由下面的filePath
指定):
... function (filePath){ messages = jsonfile.readFileSync(filePath); } ...
如何让我的函数接受这个文件path,并以我的模块能够find的方式处理它,因为我的函数永远不会知道用户的应用程序文件将存储在哪里?
如果你正在编写一个节点库,那么你的模块将被用户的应用程序需要,并保存在node_modules
文件夹中。 需要注意的是,代码只是在用户的应用程序中运行的代码,因此path将与用户的应用程序有关。
例如:让我们创build两个模块, echo-file
和user-app
,将自己的文件夹和自己的package.json
作为自己的项目。 这里有两个模块的简单文件夹结构。
workspace |- echo-file |- index.js |- package.json |- user-app |- index.js |- package.json |- userfile.txt
echo-file
模块
workspace/echo-file/package.json
{ "name": "echo-file", "version": "1.0.0", "description": "", "main": "index.js", "scripts": {"test": "echo \"Error: no test specified\" && exit 1"}, "author": "", "license": "ISC" }
workspace/echo-file/index.js
(模块的入口点)
const fs = require('fs'); // module.exports defines what your modules exposes to other modules that will use your module module.exports = function (filePath) { return fs.readFileSync(filePath).toString(); }
user-app
模块
NPM允许您从文件夹安装软件包。 它会将本地项目复制到您的node_modules
文件夹,然后用户可以require
它。
在初始化这个npm项目之后,你可以使用npm install --save ../echo-file
,并将它作为依赖添加到用户的应用程序中。
workspace/user-app/package.json
{ "name": "user-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": {"test": "echo \"Error: no test specified\" && exit 1"}, "author": "", "license": "ISC", "dependencies": { "echo-file": "file:///C:\\Users\\Rico\\workspace\\echo-file" } }
workspace/user-app/userfile.txt
hello there
workspace/user-app/index.js
const lib = require('echo-file'); // require console.log(lib('userfile.txt')); // use module; outputs `hello there` as expected
如何让我的函数接受这个文件path,并以我的模块能够find的方式处理它,因为我的函数永远不会知道用户的应用程序文件将存储在哪里?
所以长话短说:文件path将相对于用户的应用程序文件夹。
当你的模块是npm install
,它复制到node_modules
。 当给你的模块一个文件path时,它将是相对于该项目。 节点遵循commonJS
模块定义 。 EggHead也有一个很好的教程 。
希望这可以帮助!
如何使用绝对path?
如果你在yourapp/lib/index.js.
写的yourapp/lib/index.js.
path.join(__dirname, '../../../xx.json');