2017-02-20 48 views
2

我正在創建一個應用程序可以導入的節點模塊(通過npm install)。我的模塊中的功能將接受在用戶的應用程序設置(如下面filePath指定)一個以.json文件的位置:如何從節點模塊中加載用戶特定的文件?

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

如何讓我的函數接受這個文件的路徑和進程它以某種方式讓我的模塊能夠找到它,因爲我的功能永遠不會知道用戶的應用程序文件將存儲在哪裏?

+1

要求它是一個完整的路徑?該應用程序只能傳遞'path.join(__ dirname,...)'。 – Ryan

回答

1

如果您正在編寫節點庫,那麼您的模塊將由require d由用戶的應用程序,因此保存在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(); 
} 

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 definitionEggHead also has a good tutorial就可以了。

希望這會有所幫助!

0

如何使用絕對路徑?

,如果你在寫yourapp/lib/index.js.

path.join(__dirname, '../../../xx.json'); 
相關問題