Menu
CoddyTech

الوحدات المضمنة

جزء من قسم أساسيات Node.js في رحلة Node.js على Coddy. الدرس 9 من 33.

ستُحفَظ ملاحظاتك قريبًا في ملف، وتختلف مسارات الملفات من جهاز إلى آخر.

تأتي Node مع وحداتها الخاصة لهذا الغرض. تستوردها كما تستورد ملفاتك، باستخدام البادئة node: ومن دون الحاجة إلى تثبيت أي شيء. تجمع path.join أجزاء المسار باستخدام الفاصل المناسب، وتُرجع path.basename الجزء الأخير، ويشير os.homedir() إلى مجلدك الرئيسي، بينما يشير process.cwd() إلى المجلد الذي يعمل فيه البرنامج.

import os from 'node:os';
import path from 'node:path';

const file = path.join(os.homedir(), 'photos', 'cat.png');
console.log(file); // /home/ada/photos/cat.png
console.log(path.basename(file)); // cat.png

تضع path.join شرطة مائلة واحدة بين الأجزاء، لذا لن تحصل أبدًا على photoscat.png.

challenge icon

التحدي

سهل
  • يطبع الأمر الجديد where المسار الكامل للملف notes.json في المجلد الحالي: path.join(process.cwd(), 'notes.json').
  • يطبع السطر الثاني الاسم الأساسي لذلك المسار.

نفّذ node notes.js where. الملف غير موجود بعد: ينشئه الفصل 3.

جرّب بنفسك

// تبدأ أداة ملاحظاتك هنا.
import { formatNote } from './format.js';
import store from './store.js';

const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');

if (command === 'add') {
    const n = store.add(text);
    console.log(`Adding: ${formatNote(n, text)}`);
} else if (command === 'list') {
    const owner = process.env.NOTES_OWNER ?? 'you';
    console.log(`Notes for ${owner}`);
    if (store.notes.length === 0) {
        console.log('No notes yet');
    }
    store.notes.forEach((note, i) => console.log(formatNote(i + 1, note)));
} else {
    if (command) {
        console.error(`Unknown command: ${command}`);
    }
    console.error('Usage: node notes.js <command> [words]');
    process.exit(1);
}
quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس أساسيات Node.js

تدرّب بنفسك: Playground لـ Express