10 Ocak 2018 Çarşamba

Node.js dersleri 6 - process.exit(), path module, util module, process.argv

13 - process.exit() - How to exit a Node.js script

Normally a Node.js script stops running when it reaches the end of the script and when there are no more event handlers waiting for events. What if you want the script to stop earlier?
It's quite easy.
The built-on process module has a method called exit:
examples/node/process_exit.js
process.exit(-1);

14 - path module

http://www.java2s.com/Tutorials/Javascript/Node.js_Tutorial/1050__Node.js_Path_Module.htm

15 - util module

http://www.java2s.com/Tutorials/Javascript/Node.js_Tutorial/1080__Node.js_util_Module.htm
The util module'ü işimize çok yarayacak method'lar içerir. Util modülünü kullanabilmek için önce require('util') diyerek bu module'ü include etmeliyiz.
util.log()
To log out something to the console with a timestamp, you can use the util.log function. (Console'a timestamp ile log yazmak için util.log() fonksiyonunu kullanırız.)
var util = require('util');
util.log('sample message');
Yukarıdaki kod şu output'u verir:
http://www.java2s.com/Tutorials/JavascriptImage/myResult/D/DESCRIPTION__BEB12BB24105457296F7.PNG


util.format
The util.format() method returns a formatted string using the first argument as a printf-like format. (util.format() fonksiyonu, C ve C++'daki printf() fonksiyonuna benzer.)
Popular placeholders are %s (used for strings) and %d (used for numbers).
  • %s - String.
  • %d - Number (both integer and float).
  • %% - single percent sign ('%'). This does not consume an argument.
( util.format() method'unun aldığı ilk parametre bir string'dir, bu string sıfır veya daha fazla placeholder içerir. util.format method'unun aldığı diğer parametreler string'deki placeholder'ların yerine koyulur(replace edilir).  )
var util = require('util');
var name = 'CSS';
var a = 33;
console.log(util.format('%s has %d attributes', name, a)); // util.format() returns the string "CSS has 33 attributes". console.log() bu string'i argument olarak alır ve console'a yazar.
Yukarıdaki kod console'a şunu yazar.
http://www.java2s.com/Tutorials/JavascriptImage/myResult/U/UTIL_FORMAT__310B04908F921D126679.PNG

 If the placeholder does not have a corresponding argument, the placeholder is not replaced.
util.format('%s:%s', 'foo');
 // Returns 'foo:%s'


Extra:
util has a few functions to check if something is of a particular type (isArray, isDate, isError).
util.isArray() method'u, parametre olarak Array alırsa true return eder, otherwise false return eder.
util.isDate() method'u, parametre olarak Date alırsa true return eder, otherwise false return eder.
util.isError() method'u, parametre olarak Error object alırsa true return eder, otherwise false return eder.
var util = require('util');
console.log(util.isArray([])); // true
console.log(util.isArray({ length: 0 })); // false
console.log(util.isDate(new Date())); // true
console.log(util.isDate({})); // false
console.log(util.isError(new Error('This is an error'))); // true
console.log(util.isError({ message: 'I have a message' })); // false
util.debug(string)
A synchronous output function. Will block the process and output string immediately to stderr. ( Stderr'a log yazmak için kullanılır. Senkron olarak çalıştığı için, process'i durdurur sonra log'a yazar sonra process çalışmaya kaldığı yerden devam eder. ) Example :   require('util').debug('message on stderr');
util.inspect(object, showHidden=false, depth=2)
Return a string representation of object, which is useful for debugging. If showHidden is true, then the object's non-enumerable properties will be shown too. If depth is provided, it tells inspect how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. The default is to only recurse twice. To make it recurse indefinitely, pass in null for depth.
( Bu method, bir object'in string representation'ını return eder. Return edilecek string'de, object'in sahip olduğu non-enumerable member'ların da olmasını istiyorsak, 2. parametre olarak true vermeliyiz. )
Örneğin util object'i incelemek için bu object'i temsil eden bir string'i console'a şöyle yazdırırız :
var util = require('util');
console.log(util.inspect(util, true, null));
Node REPL komut satırından console.log(util.inspect(util, true, null));   komutunu çalıştırarak da util object'in string representation'ını incelyebiliriz.
util.inherits()
Note: usage of util.inherits() is discouraged. Please use the ES6(EcmaScript 6)  class and extends keywords to get language level inheritance support. Also note that the two styles are semantically incompatible.
util.inherits breaks the prototype chain. A fix does not seem useful, since ES6 extends provides language level support for the same functionality.
(util.inherits() method'unun kullanılması tavsiye edilmez. class veya extend keyword'lerini kullanarak language seviyesinde bir inheritance gerçekleştirmeliyiz. )
util.inherits(constructor, superConstructor)
Inherits the prototype methods from one constructor into another. The prototype of constructor will be set to a new object created from superConstructor.(1.parametre, 2.parametre'den miras alır. 1.parametre'deki constructor function'ın prototype'ı, 2.parametredeki constructor function kullanılarak yaratılan bir object'e set edilir. )

16 - process.argv

http://code-maven.com/argv-raw-command-line-arguments-in-nodejs
Bunu kullanarak, komut satırına girilen komuta, kod içerisinden erişebiliriz.
Client-side JS'de bu komuta ihtiyaç duyulmayabilir, ancak server-side JS'de bu komuta ihtiyaç vardır.
Node.js'deki global object'lerden olan process object'in sahip olduğu argv isimli array, komut satırına yazılan tüm parametreleri tutar.
example.js dosyamızın içeriği şu olsun :   console.log(process.argv);
Komut satırına şu komutu girerek example isimli modülümüzü çalıştırınca:
node example.js -dv --port NUMBER --dir PATH file1 file2
Console'a şu output yazılır:
[ 'node',
 'example.js',
 '-dv',
 '--port',
 'NUMBER',
 '--dir',
 'PATH',
 'file1',
 'file2' ]
Note:
  • The first element is always node itself.
  • The second element is always the file being executed.
  • The rest of the elements are the values supplied on the command line after the name of the file being executed.
Basically this is the list of all the values that were typed in on the command line.
You can loop over the array using for or forEach and extract the values. This might work well in the most simple cases, but once the parameters become complex, it will be better to use a higher level library.
I found a minimistnomnom, and yargs (the successor of node-optimist) just to name a few.
Örnek : Kullanıcının komut satırından bir node programını çalıştırırken 1 adet argument girdiğinden emin olmak istiyoruz diyelim. Örneğin node example.js omer diye bir komut girilmesini bekliyoruz diyelim.  Kullanıcının extradan 1 adet argument'i girip girmediğini check etmek için aşağıdaki gibi bir kod yazarız:
example.js
if (process.argv.length <= 2) {
// ekstra argument girilmemiştir. Kullanıcıyı uyar ve programı bitir.
   console.log("Usage: " + __filename + " ISIM");
   process.exit(-1);
}
//beklediğimiz argument girilmiştir. Bu argument'i alıp console yazdırırız.
var param = process.argv[2];
console.log('Param: ' + param);
This is how the execution works:
$ node example.js
Usage: /home/gabor/code-maven/examples/node/example.js ISIM
$ node example.js omer

Param: omer

Hiç yorum yok:

Yorum Gönder