קורס Node.JS שיעור תרגול סביבת העבודה


זהו נושא דיון מלווה לערך המקורי שב־https://www.tocode.co.il/bundles/25/lessons/18-lab-environment

היי ינון אני מנסה לכתוב את תוכנית מספר אחת, אני לא בטוח איך אני אמור לשלוף את הנתונים, הנה מה שאני מנסה.

אני לא בטוח איך אני אמור לשלוף את המידע באמצעות רגולר אקספרשיין, תחת איזה ערך אני מחפש?

const { spawn } = require('child_process');
const path = 'C:/Windows/System32/ipconfig.exe';

const ping = spawn(
    path
)


ping.stdout.on('data', (data) => {
    const out = data.toString('utf8');
   // console.log(out);
    const match = out.match(/IPv4 Address. . . . . . . . . . . :=(\d+)/);

    console.log(match);
});

הי,
אין לי ipconfig מותקן על המכונה שלי כי אני בלינוקס. יכול להדביק כאן פלט לדוגמה של ipconfig (למשל את מה שהודפס לך מה console.log(out) שמופיע שם בהערה)?

היי ינון , זה הפתרון שלי לתרגיל 1
אני על מחשב mac אז הדרך שמצאתי היא לקרוא דרך curl לכתובת ipconfig.me
עשיתי קודם בדיקה שאכן curl נמצא בנתיב ואז קראתי לפונקציה שמפעילה אותו ומחזירה את כתובת הip של השרת.

זה הקובץ הראשי של הפרוייקט:

// index.js

const express = require("express")
const app = express()
const port = process.env.PORT || 3000

app.get("/", (_req, res) => {
    res.status(200).send(`<h1>welcome</h1><ul><li><a href="/showip">show machine ip</a></li></ul>`)
})

app.get("/showip", async (_req, res) => {
    try{
        const ip = await require("./routes/ipRoute")()
        res.status(200).send(`machine ip is ${ip}`)
    }catch(err){
        res.status(500).send(`cannod find ip... some error on serve side\n${err}` )
    }
})

app.listen(port, () => console.log(`server listening on localhost:${port}`))

ופה הroute שעושה את העבודה:

// routes/ipRoute.js

const { spawn, exec } = require('child_process');
const CURL_CMD = "/usr/bin/curl"
const CONFIG_URL = "ifconfig.me"
let ip = null

async function getIp() {
    try {
        if (ip) return ip
        await findCurlCmd()
        return await getMachineIP()
    } catch (err) {
        throw new Error(err)
    }
}

function findCurlCmd() {
    return new Promise((resolve, reject) => {
        exec(`find ${CURL_CMD}`, (err, _out) => {
            if (err) {
                console.log("cannot find curl command at ", CURL_CMD)
                reject(`cannot find curl command at ${CURL_CMD}`)
            }
            resolve()
        })
    })
}

function getMachineIP() {
    return new Promise((resolve, reject) => {
        const proc = spawn(CURL_CMD, [CONFIG_URL]);

        proc.stdout.on('data', (data) => {
            const out = data.toString();
            ip = out
        });

        proc.on('error', (code) => {
            console.log(`there was an error while executing "curl ${CONFIG_URL}"`)
            return reject("error on server " + code)
        });

        proc.on('exit', () => {
            if(ip){
                console.log(`Found ip = ${ip}`);
                return resolve(ip)
            }
            reject("ip not found")
        });

    })
}

module.exports = getIp

הי

בגדול על מק עדיף להפעיל /sbin/ifconfig - הוא מראה גם כתובות IP פנימיות ולא דורש חיבור לרשת

חוץ מזה אהבתי איך שעטפת את ה API של נוד ב Promise. מאוד מומלץ לעשות את המשחקים האלה ולתרגל את ההמרות בין Promises ל async/await