gpt4 book ai didi

javascript - 如何从 Node 模块中加载用户特定的文件?

转载 作者:行者123 更新时间:2023-11-29 23:53:11 24 4
gpt4 key购买 nike

我正在创建一个应用程序可以导入的 Node 模块(通过 npm install)。我的模块中的一个函数将接受在用户应用程序中设置的 .json 文件的位置(由下面的 filePath 指定):

...
function (filePath){
messages = jsonfile.readFileSync(filePath);
}
...

如果我的函数永远不知道用户的应用程序文件将存储在哪里,我如何允许我的函数接受这个文件路径并以我的模块能够找到它的方式处理它?<​​/p >

最佳答案

如果您正在编写一个 Node 库,那么您的模块将被用户的应用程序要求,并因此保存在node_modules 文件夹中。需要注意的是,您的代码只是成为在用户应用程序中运行的代码,因此路径将是相对于用户应用程序的。

例如:让我们制作两个模块,echo-fileuser-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();
}

用户应用模块

NPM 允许您从文件夹安装包。它会将本地项目复制到您的 node_modules 文件夹中,然后用户可以要求它。

初始化此 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

How do I allow my function to accept this file path and process it in a way that my module will be able to find it, given that my function will never know where the users' application file will be stored?

长话短说:文件路径将相对于用户的应用程序文件夹。

当您的模块被 npm install 编辑时,它会复制到 node_modules。当为您的模块提供文件路径时,它将是相对于项目的。 Node 遵循 commonJS module definition . EggHead also has a good tutorial在上面。

希望这对您有所帮助!

关于javascript - 如何从 Node 模块中加载用户特定的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42336396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com