10 Ocak 2018 Çarşamba

Node.js dersleri 1 - Node.js kurulumu, temel kavramlar, hello world node.js örnek

1 -  Installation of Node.js

http://yeoman.io/codelab/setup.html
Windows'da node'un ve npm'in yüklü olup olmadığını check etmek için aşağıdaki komutu çalıştırırız komut satırında.
node --version && npm --version
If you need to upgrade or install Node, the easiest way is to use an installer for your platform. (https://nodejs.org/en/ sitesinden .exe indirip node.js'yi yükleriz kolaylıkla.   )
The npm package manager is bundled with Node, although you might need to update it. Some Node versions ship with rather old versions of npm. You can update npm using this command: ( Node ile birlikte npm ( node package manager) de gelir. Ancak bununla gelen npm'in versiyonu genellikle eskidir. Dolayısıyla npm'i aşağıdaki komutu çalıştırarak güncellemeliyiz.)

npm install --global npm@latest
http://www.nodebeginner.org/
http://nodeguide.com/beginner.html

Server yaratmak için bir module yazalım. Module ve file ismi aynıdır. server.js dosyası oluşturup içine aşağıdaki kodu yazalım, dolayısıyla server diye bir module'e sahip olacağız. Bu dosyaya şunu yazalım :
var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);
That's it! You just wrote a working HTTP server. Now, execute your script with Node.js: ( Bu kadar kolay işte! Artık bizim de çalışan bir HTTP server'ımız var. Haydi aşağıdaki komutu vererek bu kodu çalıştırarak server'ı çalıştıralım. server.js dosyasını örneğin Desktop'a koyduysak, komut satırından Desktop'a gelmeliyiz. Sonra yazdığımız kodu Node.js ile çalıştırmak için aşağıdaki komutu çalıştırırız komut satırında. Bu kodu çalıştırdıktan sonra browser'ı açıp şu adrese gidelim : http://localhost:8888/ . Açılan web sayfasında Hello World yazacaktır.Server'dan gelen cevaptır bu.  )
node server.js
Another hello world http server example
hello_http.js dosyası yaratıp bu dosyaya şu kodu yazalım:
var http = require('http');
var server = http.createServer(function(req, res) {
  res.writeHead(200);
  res.end('Hello Http');
});
server.listen(8080);
Komut satırına şunu yazarak yukarıdaki kodu çalıştırabiliriz.
$ node hello_http.js
The first thing you'll notice is that this program, unlike our first one, doesn't exit right away. That's because a node program will always run until it's certain that no further events are possible. In this case the open http server is the source of events that will keep things going.
Server'ı test etmek için, http://localhost:8080/ url'ine gideriz browser'da, böylece bu adrese deploy etmiş olduğumuz server'a get request göndermiş oluruz. Açılan sayfada server'dan gelen 'Hello Http' 'yi görürüz, bu server'dan gelen response'dır. Alternatif olarak curl'ü kullanarak (aşağıdaki komutu çalıştırarak) da server'ımızı test edebiliriz:
$ curl localhost:8080
Hello Http
What is curl? A tool and a library (usable from many languages) for client-side URL transfers, supporting FTP, FTPS, HTTP, HTTPS, TELNET, DICT, FILE and LDAP. curl is used in command lines or scripts to transfer data.
Şimdi server kodumuzu inceleyelim.
In the first line, we include the http core module and assign it to a variable called http. In other words, the first line requires the http module that ships with Node.js and makes it accessible through the variable http. ( var http = require('http'); diyerek, http modülünü include edip http isimli bir variable'a assign ettik, variable ismini kendimiz seçtik başka bir isim de seçebilirdik. Diğer bir deyişle, Node.js ile birlikte gelen built-in module http'yi include edip, bu module'e http isimli bir variable'dan erişilmesini sağlıyoruz. )
Next we create a variable called server and call one of the functions the http module offers http.createServer().This function returns an object. The argument passed into this call is a closure that is called whenever an http request comes in. ( Sonra http isimli variable'ımızın createServer() method'unu çağırdık, aslında import ettiğimiz http modülünün createServer() method'unu çağırmış olduk. createServer() fonksiyonu bir object return eder. Tanımladığımız server isimli variable bu fonksiyonun return ettiği object'e refer eder.  createServer() methoduna argument olarak anonymous bir fonksiyon verdik. serverımıza bir request geldiğinde yani biz browser'dan localhost:8080 adresini açtığımızda, createServer() fonksiyonunun aldığı parametre olan anonymous fonksiyon çalıştırılır. )
The object which createServer() returned has a method named listen, and takes a numeric value which indicates the port number our HTTP server is going to listen on. We call server.listen(8080) to tell node.js the port on which we want our server to run. If you want to run on port 80, your program needs to be executed as root. (createServer() method'unun return ettiği object, listen() isimli bir fonksiyona sahiptir, listen() fonksiyonuna argument olarak server'ımızın çalışmasını istediğimiz port numarasını veririz. server.listen(8080) diyerek server'ımızın 8080 port'unda çalışmasını, server'ımızın 8080 port'una deploy edilmesini sağlarız. Artık server kodumuz 8080 port'unda çalışmakta ve gelecek request'leri beklemektedir. )
Now when you point your browser to 'localhost:8080', the connection closure is invoked with a req and res object. The req is a readable stream that emits 'data' events for each incoming piece of data (like a form submission or file upload). The res object is a writable stream that is used to send data back to the client. In our case we are simply sending a 200 OK header, as well as the body 'Hello Http'.(Browser'da localhost:8080 açtığımızda, req ve res object'leri ile bağlantı sağlanır. req, browser'dan server'a gönderilen request object'dir, res ise server'dan browser'a gönderilecek response object'dir. req bir readable stream'dir. Gelen herbir veri için örneğin gelen for submission'ları ve file upload'lar için bir data event emit eder. res object ise writable bir stream'dir, server'dan browser'a veri göndermek için kullanılır. Yukarıdaki örnekte server'dan browser'a gönderdiğimiz response object'in header'ında 200 status'ü ve body'sinde 'Hello Http' gönderdik. )
Analyzing our HTTP server
We could have written the code that starts our server and makes it listen at port 8888 like this:
var http = require("http");

var server = http.createServer();
server.listen(8888);
That would start an HTTP server listening at port 8888 and doing nothing else (not even answering any incoming requests).
Bu örneklerde de createServer() fonksiyonuna argument olarak anonymous bir fonksiyon verdik.
We pass the function say as the first parameter to the execute function. Not the return value of say, but say itself! Thus, say becomes the local variable someFunction within execute, and execute can call the function in this variable by issuing someFunction() (adding brackets). Of course, because say takes one parameter, execute can pass such a parameter when calling someFunction. (Javascript'de fonksiyon'lara argument olarak başka bir fonksiyonu verebiliriz. Aaşağıdaki örnekte, say() isimli bir fonksiyon tanımladık. Sonra execute isimli bir fonksiyon tanımladık, bu fonksiyonun alacağı ilk argument bir fonksiyon olacak şekilde tanımladık. execute(say, "Hello"); diyerek execute fonksiyonunu çağırdığımızda, say fonksiyonu execute fonksiyonunun içindeki local variable olan someFunction olur. Bu variable'daki fonksiyonu çağırmak için () işaretlerini ekleyerek yani someFunction() diyerek say fonksiyonunu çağırırız. )
function say(word) {
  console.log(word);
}

function execute(someFunction, value) {
  someFunction(value);
}

execute(say, "Hello");  // fonksiyonun ilk parametresi say() fonksiyonu'dur.
We can, as we just did, pass a function as a parameter to another function by its name. But we don't have to take this indirection of first defining, then passing it - we can define and pass a function as a parameter to another function in-place:
function execute(someFunction, value) {
  someFunction(value);
}

execute(function(word){ console.log(word) }, "Hello");
This way, we don't even need to give the function a name, which is why this is called an anonymous function.
In JavaScript, we can pass a function as a parameter when calling another function. We can do this by assigning our function to a variable which we pass later, or by defining the function to pass in-place.
We could write the same server code by refactoring our it to:
var http = require("http");

function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888);
Maybe now is a good moment to ask: Why are we doing it that way? ( İşte şu an tam da şu soruyu sormak için doğru zaman! : Neden bir fonksiyon tanımlayıp da bu fonksiyonu createServer() fonksiyonuna argument olarak vermiyoruz da ,createServer() fonksiyonuna anonymous fonksiyon veriyoruz. Bu ikisi arasında fark var mıdır? Evet vardır!! Hem de çok önemli bir fark vardır. Çünkü createServer fonksiyonumuzun asenkron çalışması için bu fonksiyona anonymous fonksiyon vermeliyiz. Eğer böyle yapmazsa, createServer() fonksiyonuna argument olarak daha önce tanımladığımız bir fonksiyonu verirsek, kodumuz synchronize çalışır, dolayısıyla createServer() method'unun tamamlanmasını bekleriz, bu method tamamlanmadan sonraki satırlardaki kodlar çalışmaz.  )

1 yorum:

  1. Node.js ortaya çıktıktan sonra artık Javascript sadece kullanıcı tarafında kullanılan basit bir programlama dili olmaktan çıkarak veri tabanı işlemleri gibi Back End işlemlerinin yapılabildiği bir dil haline gelmiştir. Javascript neden popüler şeklinde bir soru soracak olursanız da öğrenmesi kolay, olay tabanlı ve arkasında büyük bir topluluk olan bir dil olması denilebilir.

    YanıtlaSil