如果您正在編寫節點庫,那麼您的模塊將由require
d由用戶的應用程序,因此保存在node_modules
文件夾中。需要注意的是,您的代碼只是在用戶的應用程序中運行的代碼,因此路徑將相對於用戶的應用程序。
例如:我們製作兩個模塊,分別爲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
如何讓我的函數接受的方式這個文件的路徑和過程中它是MY M odule將能夠找到它,因爲我的功能永遠不會知道用戶的應用程序文件將存儲在哪裏?
長期以來的故事:文件路徑將相對於用戶的應用程序文件夾。
當你的模塊是npm install
ed,它複製到node_modules
。當給你的模塊一個文件路徑時,它將是相對於該項目。節點遵循commonJS
module definition。 EggHead also has a good tutorial就可以了。
希望這會有所幫助!
要求它是一個完整的路徑?該應用程序只能傳遞'path.join(__ dirname,...)'。 – Ryan