Bu ders için video bulunmamaktadır.
Ders İçeriği
Dosya Sistemi (File System) Modülü
Node.js'in fs
modülü, dosya sistemi işlemleri için kapsamlı bir API sağlar. Bu modül ile dosya okuma, yazma, oluşturma, silme ve dizin işlemleri yapabilirsiniz. Hem senkron hem de asenkron versiyonları mevcuttur.
Dosya Okuma İşlemleri
Dosya okuma işlemleri Node.js'te en sık kullanılan işlemlerden biridir. Farklı yöntemlerle dosya okuyabilirsiniz:
const fs = require('fs');
const path = require('path');
// Asenkron dosya okuma
fs.readFile('ornek.txt', 'utf8', (err, data) => {
if (err) {
console.error('Dosya okuma hatası:', err);
return;
}
console.log('Dosya içeriği:', data);
});
// Promise tabanlı dosya okuma
const fsPromises = require('fs').promises;
async function dosyaOku(dosyaYolu) {
try {
const data = await fsPromises.readFile(dosyaYolu, 'utf8');
console.log('Dosya içeriği:', data);
return data;
} catch (error) {
console.error('Dosya okuma hatası:', error);
throw error;
}
}
// Senkron dosya okuma (dikkatli kullanın!)
try {
const data = fs.readFileSync('ornek.txt', 'utf8');
console.log('Senkron okuma:', data);
} catch (error) {
console.error('Senkron okuma hatası:', error);
}
// Stream ile büyük dosya okuma
const readStream = fs.createReadStream('buyuk_dosya.txt', { encoding: 'utf8' });
readStream.on('data', (chunk) => {
console.log('Veri parçası:', chunk.length, 'karakter');
});
readStream.on('end', () => {
console.log('Dosya okuma tamamlandı');
});
readStream.on('error', (err) => {
console.error('Stream okuma hatası:', err);
});
Dosya Yazma İşlemleri
Dosya yazma işlemleri de benzer şekilde asenkron ve senkron olarak yapılabilir:
const fs = require('fs');
// Asenkron dosya yazma
const icerik = 'Bu içerik Node.js ile yazıldı!\nYeni satır eklendi.';
fs.writeFile('yeni_dosya.txt', icerik, 'utf8', (err) => {
if (err) {
console.error('Dosya yazma hatası:', err);
return;
}
console.log('Dosya başarıyla yazıldı!');
});
// Promise tabanlı dosya yazma
async function dosyaYaz(dosyaYolu, icerik) {
try {
await fsPromises.writeFile(dosyaYolu, icerik, 'utf8');
console.log('Dosya başarıyla yazıldı:', dosyaYolu);
} catch (error) {
console.error('Dosya yazma hatası:', error);
}
}
// Dosya sonuna ekleme (append)
fs.appendFile('log.txt', 'Yeni log girişi: ' + new Date().toISOString() + '\n', (err) => {
if (err) {
console.error('Dosya ekleme hatası:', err);
return;
}
console.log('Log girişi eklendi');
});
// Stream ile yazma (büyük dosyalar için)
const writeStream = fs.createWriteStream('output.txt');
writeStream.write('İlk satır\n');
writeStream.write('İkinci satır\n');
writeStream.write('Üçüncü satır\n');
writeStream.end(() => {
console.log('Stream yazma tamamlandı');
});
writeStream.on('error', (err) => {
console.error('Stream yazma hatası:', err);
});
Dizin İşlemleri
Klasör oluşturma, listeleme ve silme işlemleri:
const fs = require('fs');
const path = require('path');
// Dizin oluşturma
fs.mkdir('yeni_klasor', { recursive: true }, (err) => {
if (err) {
console.error('Dizin oluşturma hatası:', err);
return;
}
console.log('Dizin oluşturuldu');
});
// Dizin içeriğini listeleme
fs.readdir('.', (err, files) => {
if (err) {
console.error('Dizin okuma hatası:', err);
return;
}
console.log('Mevcut dizin içeriği:');
files.forEach(file => {
const filePath = path.join('.', file);
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
console.log('📁', file);
} else {
console.log('📄', file, `(${stats.size} bytes)`);
}
});
});
// Dosya/dizin bilgilerini alma
fs.stat('ornek.txt', (err, stats) => {
if (err) {
console.error('Stat hatası:', err);
return;
}
console.log('Dosya bilgileri:');
console.log('Boyut:', stats.size, 'bytes');
console.log('Oluşturma tarihi:', stats.birthtime);
console.log('Değiştirilme tarihi:', stats.mtime);
console.log('Dizin mi?', stats.isDirectory());
console.log('Dosya mı?', stats.isFile());
});
// Dosya/dizin silme
fs.unlink('silinecek_dosya.txt', (err) => {
if (err) {
console.error('Dosya silme hatası:', err);
return;
}
console.log('Dosya silindi');
});
// Dizin silme (boş dizin)
fs.rmdir('silinecek_klasor', (err) => {
if (err) {
console.error('Dizin silme hatası:', err);
return;
}
console.log('Dizin silindi');
});
Path Modülü
Path modülü, dosya yolları ile çalışmak için kullanılır. İşletim sistemi bağımsız yol işlemleri yapmanızı sağlar:
const path = require('path');
// Yol birleştirme
const fullPath = path.join('/users', 'john', 'documents', 'file.txt');
console.log('Birleştirilmiş yol:', fullPath);
// Mutlak yol oluşturma
const absolutePath = path.resolve('dosya.txt');
console.log('Mutlak yol:', absolutePath);
// Dosya uzantısı alma
const extension = path.extname('dosya.txt');
console.log('Uzantı:', extension); // .txt
// Dosya adı alma
const filename = path.basename('/path/to/file.txt');
console.log('Dosya adı:', filename); // file.txt
// Dizin adı alma
const dirname = path.dirname('/path/to/file.txt');
console.log('Dizin:', dirname); // /path/to
// Yol parçalarına ayırma
const parsed = path.parse('/users/john/documents/file.txt');
console.log('Parçalanmış yol:', parsed);
// {
// root: '/',
// dir: '/users/john/documents',
// base: 'file.txt',
// ext: '.txt',
// name: 'file'
// }
// İşletim sistemi ayırıcısı
console.log('Yol ayırıcısı:', path.sep);
// Göreli yol hesaplama
const relativePath = path.relative('/users/john', '/users/john/documents/file.txt');
console.log('Göreli yol:', relativePath); // documents/file.txt
HTTP Modülü ve Web Sunucusu
Node.js'in http
modülü, HTTP sunucuları ve istemcileri oluşturmak için kullanılır. Bu modül ile web uygulamaları geliştirebilirsiniz:
Basit HTTP Sunucusu
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
// Basit sunucu oluşturma
const server = http.createServer((req, res) => {
// İstek bilgilerini logla
console.log(`${req.method} ${req.url} - ${new Date().toISOString()}`);
// CORS başlıkları ekle
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
// URL'yi parse et
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
const query = parsedUrl.query;
// Routing
if (pathname === '/') {
// Ana sayfa
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`
<h1>Node.js HTTP Sunucusu</h1>
<p>Hoş geldiniz! Bu sayfa Node.js ile oluşturulmuştur.</p>
<ul>
<li><a href="/about">Hakkında</a></li>
<li><a href="/api/users">Kullanıcılar API</a></li>
<li><a href="/time">Şu anki zaman</a></li>
</ul>
`);
} else if (pathname === '/about') {
// Hakkında sayfası
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`
<h1>Hakkında</h1>
<p>Bu Node.js öğrenme projesidir.</p>
<a href="/">Ana sayfaya dön</a>
`);
} else if (pathname === '/time') {
// Zaman API'si
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({
timestamp: Date.now(),
date: new Date().toISOString(),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
}));
} else if (pathname === '/api/users') {
// Kullanıcılar API'si
const users = [
{ id: 1, name: 'Ali Veli', email: 'ali@example.com' },
{ id: 2, name: 'Ayşe Fatma', email: 'ayse@example.com' },
{ id: 3, name: 'Mehmet Can', email: 'mehmet@example.com' }
];
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(users, null, 2));
} else {
// 404 Not Found
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`
<h1>404 - Sayfa Bulunamadı</h1>
<p>Aradığınız sayfa mevcut değil.</p>
<a href="/">Ana sayfaya dön</a>
`);
}
});
// Sunucuyu başlat
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Sunucu http://localhost:${PORT} adresinde çalışıyor`);
});
// Hata yönetimi
server.on('error', (err) => {
console.error('Sunucu hatası:', err);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM sinyali alındı, sunucu kapatılıyor...');
server.close(() => {
console.log('Sunucu kapatıldı');
process.exit(0);
});
});
POST İstekleri ve Form Verisi
POST isteklerini işlemek ve form verilerini almak:
const http = require('http');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
// HTML form sayfası
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`
<!DOCTYPE html>
<html>
<head>
<title>Node.js Form Örneği</title>
<meta charset="utf-8">
</head>
<body>
<h1>Kullanıcı Kayıt Formu</h1>
<form method="POST" action="/submit">
<p>
<label>Ad: <input type="text" name="name" required></label>
</p>
<p>
<label>E-posta: <input type="email" name="email" required></label>
</p>
<p>
<label>Yaş: <input type="number" name="age" required></label>
</p>
<p>
<button type="submit">Kaydet</button>
</p>
</form>
</body>
</html>
`);
} else if (req.method === 'POST' && req.url === '/submit') {
// POST verilerini al
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
// Form verilerini parse et
const formData = querystring.parse(body);
console.log('Alınan form verisi:', formData);
// Yanıt gönder
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`
<h1>Kayıt Başarılı!</h1>
<p>Merhaba ${formData.name}!</p>
<p>E-posta: ${formData.email}</p>
<p>Yaş: ${formData.age}</p>
<a href="/">Geri dön</a>
`);
});
} else {
// 404
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Sayfa bulunamadı');
}
});
server.listen(3000, () => {
console.log('Form sunucusu http://localhost:3000 adresinde çalışıyor');
});
JSON API Oluşturma
RESTful API endpoints oluşturma:
const http = require('http');
const url = require('url');
// Basit veritabanı simülasyonu
let users = [
{ id: 1, name: 'Ali Veli', email: 'ali@example.com', age: 25 },
{ id: 2, name: 'Ayşe Fatma', email: 'ayse@example.com', age: 30 },
{ id: 3, name: 'Mehmet Can', email: 'mehmet@example.com', age: 28 }
];
let nextId = 4;
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
const method = req.method;
// CORS başlıkları
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// API Routes
if (path === '/api/users' && method === 'GET') {
// Tüm kullanıcıları getir
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, data: users }));
} else if (path.startsWith('/api/users/') && method === 'GET') {
// Belirli kullanıcıyı getir
const id = parseInt(path.split('/')[3]);
const user = users.find(u => u.id === id);
if (user) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, data: user }));
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: false, message: 'Kullanıcı bulunamadı' }));
}
} else if (path === '/api/users' && method === 'POST') {
// Yeni kullanıcı oluştur
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const userData = JSON.parse(body);
const newUser = {
id: nextId++,
name: userData.name,
email: userData.email,
age: userData.age
};
users.push(newUser);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, data: newUser }));
} catch (error) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: false, message: 'Geçersiz JSON' }));
}
});
} else if (path.startsWith('/api/users/') && method === 'DELETE') {
// Kullanıcı sil
const id = parseInt(path.split('/')[3]);
const userIndex = users.findIndex(u => u.id === id);
if (userIndex !== -1) {
const deletedUser = users.splice(userIndex, 1)[0];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true, data: deletedUser }));
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: false, message: 'Kullanıcı bulunamadı' }));
}
} else {
// 404
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: false, message: 'Endpoint bulunamadı' }));
}
});
server.listen(3000, () => {
console.log('JSON API sunucusu http://localhost:3000 adresinde çalışıyor');
console.log('Endpoints:');
console.log('GET /api/users - Tüm kullanıcıları listele');
console.log('GET /api/users/:id - Belirli kullanıcıyı getir');
console.log('POST /api/users - Yeni kullanıcı oluştur');
console.log('DELETE /api/users/:id - Kullanıcı sil');
});
URL ve Query String İşlemleri
URL'leri parse etmek ve query string'leri işlemek:
const url = require('url');
const querystring = require('querystring');
// URL parse etme
const myUrl = 'https://example.com:8080/path/to/page?name=john&age=30&city=istanbul#section1';
const parsedUrl = url.parse(myUrl, true);
console.log('Parse edilmiş URL:', parsedUrl);
// URL bileşenleri
console.log('Protocol:', parsedUrl.protocol); // https:
console.log('Host:', parsedUrl.host); // example.com:8080
console.log('Hostname:', parsedUrl.hostname); // example.com
console.log('Port:', parsedUrl.port); // 8080
console.log('Pathname:', parsedUrl.pathname); // /path/to/page
console.log('Search:', parsedUrl.search); // ?name=john&age=30&city=istanbul
console.log('Query:', parsedUrl.query); // { name: 'john', age: '30', city: 'istanbul' }
console.log('Hash:', parsedUrl.hash); // #section1
// Query string işlemleri
const queryStr = 'name=john&age=30&city=istanbul&hobbies=reading&hobbies=gaming';
const parsed = querystring.parse(queryStr);
console.log('Parse edilmiş query:', parsed);
// { name: 'john', age: '30', city: 'istanbul', hobbies: ['reading', 'gaming'] }
// Query string oluşturma
const queryObj = {
name: 'ayse',
age: 25,
city: 'ankara',
active: true
};
const queryString = querystring.stringify(queryObj);
console.log('Oluşturulan query string:', queryString);
// name=ayse&age=25&city=ankara&active=true
// Modern URL API (Node.js 10+)
const modernUrl = new URL('https://example.com/path?name=john&age=30');
console.log('Modern URL pathname:', modernUrl.pathname);
console.log('Modern URL search params:', modernUrl.searchParams.get('name'));
// Search params ile çalışma
modernUrl.searchParams.set('city', 'istanbul');
modernUrl.searchParams.append('hobby', 'reading');
modernUrl.searchParams.append('hobby', 'gaming');
console.log('Güncellenmiş URL:', modernUrl.toString());
HTTP İstemcisi (Client) Oluşturma
Node.js ile HTTP istekleri gönderme:
const http = require('http');
const https = require('https');
// GET isteği gönderme
function httpGet(url) {
return new Promise((resolve, reject) => {
const request = http.get(url, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
resolve({
statusCode: response.statusCode,
headers: response.headers,
data: data
});
});
});
request.on('error', (error) => {
reject(error);
});
request.setTimeout(5000, () => {
request.abort();
reject(new Error('İstek zaman aşımına uğradı'));
});
});
}
// POST isteği gönderme
function httpPost(hostname, port, path, data) {
return new Promise((resolve, reject) => {
const postData = JSON.stringify(data);
const options = {
hostname: hostname,
port: port,
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
const request = http.request(options, (response) => {
let responseData = '';
response.on('data', (chunk) => {
responseData += chunk;
});
response.on('end', () => {
resolve({
statusCode: response.statusCode,
headers: response.headers,
data: responseData
});
});
});
request.on('error', (error) => {
reject(error);
});
request.write(postData);
request.end();
});
}
// Kullanım örnekleri
async function ornekIstekler() {
try {
// GET isteği
console.log('GET isteği gönderiliyor...');
const getResponse = await httpGet('http://httpbin.org/get');
console.log('GET yanıtı:', getResponse.statusCode);
// POST isteği
console.log('POST isteği gönderiliyor...');
const postData = { name: 'John', age: 30 };
const postResponse = await httpPost('httpbin.org', 80, '/post', postData);
console.log('POST yanıtı:', postResponse.statusCode);
} catch (error) {
console.error('İstek hatası:', error.message);
}
}
// ornekIstekler();