2016-07-25 14 views
0

私は無名関数を使用してファイルを必要とし、パラメータを渡すことによって、別のnodejsファイルからオブジェクトをパラメータを持つmodule.exportsはしてエクスポートした自己実行匿名関数を呼び出すようにしようとしているが、このようなオブジェクト:自己実行module.exported匿名ノード関数に引数を渡すにはどうすればよいですか?

fileThatCallsTheAnonymousSelfExecutingFunctionを: `

var parameters = { 
    filename: "UsernamesAndQueues", 
    headers: ["username", "password", "queue"], 
    columns: ["ascii", "ascii", "ascii"], 
    wordLength: 25, 
    count: 100 
}; 

var generateData = require("../scripts/generateData.js")(parameters); 

generateData.js:

// if the function does not call itself in this file, i can pass the 
// arguments normally, and it prints out the expected options. 

module.exports = (function (options) { 

    console.log("Hello %s", JSON.stringify(options)); 
    options = options || { 
          "headers": ["username", "password", "queueName"], 
          "columns": ["ascii", "ascii", "ascii"], 
          "wordLength": 26, 
          "count": 101 
         }; 

    console.log("Current options are: %s", JSON.stringify(options)); 
    // I just want to know what the arguments are for now, so I interrupt 
    process.exit(); 
    // i just want for the moment to print out the options object 
    // later on, i would like to use the options as i would parse arguments ??? options[0], options[1], options[2] etc. 

    // rest of the file that really needs the function arguments 
    console.log("something"); 
    var fs = require('fs'), 
     generate = require('csv-generate'), 
     filename = "UsernamesAndQueues", 
     csvfilestream = fs.createWriteStream("../data/" + "generated" + filename + ".csv", { flags: 'w' }), 
     error = fs.createWriteStream(__dirname + '/node.error.log', {flags: 'w'}), 
     // CSV generator (read command line arguments, create with defaults, making filename required) 
     generator = generate({ 
      header: options.headers, 
      columns: options.columns, 
      max_word_length: options.wordLength, 
      length: options.count 
     }); 

     // Redirect stdout/stderr to file 
     process.stdout.write = csvfilestream.write.bind(csvfilestream); 
     process.stderr.write = error.write.bind(error); 

     // Handle Uncaught Exceptions/Errors 
     process.on('uncaughtException', function(err){ 
      console.error((err && err.stack) ? err.stack : err); 
     }); 

     // Output CSV to stdout stream -> to file 
     generator.pipe(process.stdout); 
})(arguments[0]); 

私は関数に渡された引数を正しく処理する方法は何ですか?私はコマンドライン引数から(オプションの)コマンドライン引数を使って、このようにしてcmdラインから呼び出すこともできます。私はこのようにする方法を見つけた後、さらに引数パーザを使うことができます。

コマンドラインスクリプト(node generateData.js --headers ["param1", "param2", "param3"] --columns ["ascii", "ascii", "ascii"] --wordLength 25 --count 100)として実行できるノードスクリプト(関数)を実装するための他の提案がある場合は、モジュールが別のモジュールに関数ファイルをエクスポートし、上記のようなパラメータオブジェクト

その他の質問:私は正しく何をしていますか、間違っていますか、これらの概念をよりよく理解するために何をどこで読むことができますか?私はMozilla Devと他のサイトを見てきました。パラメータを使って自己実行する匿名関数に関するものを見つけましたが、外部ファイルから呼び出されたものはありませんでした。おそらく、私は正しいものを探していないかもしれません...

後で編集: 私はすでに関数をエクスポートし、別のファイルから呼び出してみました。これは簡単な方法です。

scriptThatRequiresTheExportedModuleAndCallsItWithParameters(引数)あなたは適切な構造を持っていない

var parameters = { 
    headers: ["username", "password", "queue"], 
    columns: ["ascii", "ascii", "ascii"], 
    word_length: 25, 
    count: 100 
}; 
// this works 
var generateUsernames = require('../scripts/generateData.js')(parameters); 

generateData.js

// this works, just exporting the function, without self-executing (calling) 
// i call the function (providing arguments) from the other file requiring it 
module.exports = function (options) { 
    console.log("Hello %s", JSON.stringify(options)); 
    options = options || { 
          "headers": ["username", "password", "queueName"], 
          "columns": ["ascii", "ascii", "ascii"], 
          "wordLength": 26, 
          "count": 101 
         }; 
    console.log("Current options are: %s", JSON.stringify(options)); 
    // exiting, because, for now, i just want to know what the arguments (options) are 
    process.exit(); 
    console.log("something"); 
    var fs = require('fs'), 
     generate = require('csv-generate'), 
     filename = "UsernamesAndQueues", 
     csvfilestream = fs.createWriteStream("../data/" + "generated" + filename + ".csv", { flags: 'w' }), 
     error = fs.createWriteStream(__dirname + '/node.error.log', {flags: 'w'}), 

    // CSV generator (read command line arguments, create with defaults, making filename required) 
    generator = generate({ 
     header: options.headers, 
     columns: options.columns, 
     max_word_length: options.wordLength, 
     length: options.count 
    }); 

    // Redirect stdout/stderr to file 
    process.stdout.write = csvfilestream.write.bind(csvfilestream); 
    process.stderr.write = error.write.bind(error); 

    // Handle Uncaught Exceptions/Errors 
    process.on('uncaughtException', function(err){ 
     console.error((err && err.stack) ? err.stack : err); 
    }); 

    // Output CSV to stdout stream -> to file 
    generator.pipe(process.stdout); 
}; 
+1

ニットピッキング:それは*自己実行*ではなく、インラインで呼び出されただけです。それに対する口語の言葉は、IIFE(インラインで呼び出される関数式)です。 –

+2

@ T.J.Crowder私はそれが*即座に*呼び出された関数式であると思った。 –

+0

@torazaburo:私は両方のことを聞いたことがありますが、私が好きで使いたいものです。 :-) –

答えて

1
:あなたは、コマンドラインからこれを実行することができ、その後

// command line module processing module 
// gendata.js 

// load the generateData module 
var gData = require('./generateData.js'); 

var options = {}; 
// some code here to process the command line arguments in process.argv 
// into the options object 

// call the other module with the command line arguments in the options object 
gData(options); 

jfriend00が指摘しているように、「あなたのコードはすぐに実行されます。後であなたのモジュールを使用する誰かがそれを呼び出すことに決めたときではありません。予想通りに使用するには、module.exportsrequireの機能を割り当てる必要があります。

「generateData.js [list of arguments]」の動作を取得するには、コンテキストがCLIであるかどうかをチェックする条件を追加してから、関数を呼び出すかifいいえ:

var fancyFn = function(options) { 
    ... 
}; 
if (require.main === module) { 
    fancyFn(arguments[0]); 
} else { 
    module.exports = fancyFn; 
} 
+0

[docsから](https://nodejs.org/api/modules.html#modules_accessing_the_main_module):* Node.jsから直接ファイルを実行すると、require.mainがそのモジュールに設定されます。あなたは@ jfriend00の答えを考えます。この種のロジックをモジュールファイルに保存すると、すべてのモジュールファイルにこの種のロジックが保持されます。はい、あなたは*これを行うことができます。あなたはおそらく*はしてはいけません。 – Will

+0

はい、これは可能性があります。しかし、これは物事をするための_pythonic_方法に似ていますが。 require.mainプロパティとは何ですか?私はこのことについてどこで読むことができますか? 私は上記の方法と例を試していただき、ありがとうございます。私はすでにこれがうまくいくことを知っています。回答をマークするために戻ってきます。 - ") 条件付きでは、私はcmdの行引数を解析してヘルプメニューを表示し、_options_オブジェクトを作成してfancyFnを呼び出すこともできます。 –

+0

この種のアプローチを長期間使用することの影響を考えてもいいですか?モジュールごとに1つのファイルを使用し、別のファイルにコマンドラインユーティリティを使用する代わりに) –

3

を.jsファイル。自己実行型(技術的には「インライン呼び出し」)は、モジュールを使用している誰かが呼び出すことを決定したときではなく、直ちに実行されます。通常の関数をエクスポートしたいだけで、自己実行部分はまったく必要ないと思われます。次に、モジュールの呼び出し側は、使用パターンが示すように引数を指定します。

ただ、これに変更します。

module.exports = function (options) { 

    console.log("Hello %s", JSON.stringify(options)); 
    options = options || { 
          "headers": ["username", "password", "queueName"], 
          "columns": ["ascii", "ascii", "ascii"], 
          "wordLength": 26, 
          "count": 101 
         }; 

    console.log("Current options are: %s", JSON.stringify(options)); 
    process.exit(); 
    // i just want for the moment to print out the options object 
    // later on, i would like to use the options as i would parse arguments ??? options[0], options[1], options[2] etc. 

    // rest of the file that really needs the function arguments 
    console.log("something"); 
    var fs = require('fs'), 
     generate = require('csv-generate'), 
     filename = "UsernamesAndQueues", 
     csvfilestream = fs.createWriteStream("../data/" + "generated" + filename + ".csv", { flags: 'w' }), 
     error = fs.createWriteStream(__dirname + '/node.error.log', {flags: 'w'}), 
     // CSV generator (read command line arguments, create with defaults, making filename required) 
     generator = generate({ 
      header: options.headers, 
      columns: options.columns, 
      max_word_length: options.wordLength, 
      length: options.count 
     }); 

     // Redirect stdout/stderr to file 
     process.stdout.write = csvfilestream.write.bind(csvfilestream); 
     process.stderr.write = error.write.bind(error); 

     // Handle Uncaught Exceptions/Errors 
     process.on('uncaughtException', function(err){ 
      console.error((err && err.stack) ? err.stack : err); 
     }); 

     // Output CSV to stdout stream -> to file 
     generator.pipe(process.stdout); 
}; 

P.S.残りの部分を使用しないであなたの関数の中になぜprocess.exit();があるのですか?


あなたは他の誰かが呼び出していること、コマンドラインから、あるいは定期的なモジュールとしてこれを使用することができるようにしたい場合は、コマンドライン引数を取り出し、別の小型モジュールを作ることができ、このモジュールをロードし、それを呼び出します。あなたがコマンドライン引数が仕事をしたい正確にどのように私には明らかではないが、一般的な構造はこのようになります:

node gendata.js arg1 arg2 arg3 
+0

ノードgenerateData.js [引数のリスト]でコマンドラインで関数を実行し、別のノードスクリプトでファイル(モジュール)を要求することにより、var generateData = require( 'generateData.js')(arguments)私が既に知っているgenerateData.jsの最初のコメントで述べたとおり、あなたが指摘したバージョンを試しました。私は関数を呼び出す二重使用方法を探しています。 この関数をコマンドラインでスクリプトとしてどのように実行しますか?ノード環境に入ることなく、ノードgenerateData.js [options]として? –

+0

@brainsearching - コマンドライン引数は 'process.argv'にあります。与えられたモジュールは、コマンドライン引数を処理するように要求されているのか、他の誰かが呼び出すためのモジュールであるのかを知る必要があります。私はあなたがコマンドラインのものを行い、このモジュールをロードする小さなモジュールを作ることをお勧めします。私は私の答えに例を追加します。 – jfriend00

+0

CLIの魔法の責任をモジュールの魔法から分離することを歓迎します。 – Will

関連する問題