ノードライブラリを作成している場合、モジュールはrequire
となり、ユーザーのアプリケーションでnode_modules
フォルダに保存されます。注意すべき点は、コードがユーザーのアプリケーションでコードが実行されるようになるため、パスはユーザーのアプリケーションとの相対的なものになります。
例:echo-file
とuser-app
の2つのモジュールを作成して、独自のフォルダとして、自分のプロジェクトとしてpackage.json
を作成しましょう。ここには、2つのモジュールを持つ単純なフォルダ構造があります。
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
私は私の関数は、このファイルのパスを受け入れ、その私メートル方法でそれを処理できるようにするにはどうすればよいですユーザーのアプリケーションファイルがどこに保存されるのかわからないので、それを見つけることができます。
短いので、ファイルパスはユーザーのアプリフォルダからの相対パスになります。
モジュールがnpm install
になると、node_modules
にコピーされます。あなたのモジュールにファイルパスが与えられると、それはプロジェクトとの相対パスになります。ノードはcommonJS
module definitionに従います。それにはEggHead also has a good tutorialがあります。
希望すると便利です。
で書いた場合、それは完全なパスする必要が?アプリケーションは単に 'path.join(__ dirname、...)'を渡すことができます。 – Ryan