WE_USE_JS Telegram 4874
👩‍💻 Задачка по NodeJS

Создайте приложение на Node.js, которое эмулирует систему регистрации и входа пользователей. Программа должна принимать два аргумента командной строки: "register" или "login" и имя пользователя. Если пользователь регистрируется, программа должна сохранить его в текстовый файл (users.txt). Если пользователь пытается войти в систему, программа должна проверить, зарегистрирован ли этот пользователь в файле, и вывести соответствующее сообщение.

➡️ Пример:

node app.js register Alice — добавляет пользователя Alice в файл.
node app.js login Alice — проверяет, существует ли Alice в файле, и выводит сообщение об успешном входе или ошибке.

Решение задачи ⬇️

const fs = require('fs');
const action = process.argv[2];
const username = process.argv[3];
const filePath = 'users.txt';

if (!action || !username) {
console.log('Используйте: node app.js <register|login> <username>');
process.exit(1);
}

// Функция для регистрации пользователя
function registerUser(username) {
fs.appendFile(filePath, `${username}\n`, (err) => {
if (err) {
console.error('Ошибка регистрации:', err);
process.exit(1);
}
console.log(`Пользователь ${username} зарегистрирован.`);
});
}

// Функция для входа пользователя
function loginUser(username) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Ошибка чтения файла:', err);
process.exit(1);
}

const users = data.split('\n').map(user => user.trim());
if (users.includes(username)) {
console.log(`Пользователь ${username} успешно вошёл в систему.`);
} else {
console.log(`Пользователь ${username} не найден.`);
}
});
}

// Логика обработки команд
if (action === 'register') {
registerUser(username);
} else if (action === 'login') {
loginUser(username);
} else {
console.log('Неизвестное действие. Используйте "register" или "login".');
}
Please open Telegram to view this post
VIEW IN TELEGRAM
8



tgoop.com/we_use_js/4874
Create:
Last Update:

👩‍💻 Задачка по NodeJS

Создайте приложение на Node.js, которое эмулирует систему регистрации и входа пользователей. Программа должна принимать два аргумента командной строки: "register" или "login" и имя пользователя. Если пользователь регистрируется, программа должна сохранить его в текстовый файл (users.txt). Если пользователь пытается войти в систему, программа должна проверить, зарегистрирован ли этот пользователь в файле, и вывести соответствующее сообщение.

➡️ Пример:

node app.js register Alice — добавляет пользователя Alice в файл.
node app.js login Alice — проверяет, существует ли Alice в файле, и выводит сообщение об успешном входе или ошибке.

Решение задачи ⬇️

const fs = require('fs');
const action = process.argv[2];
const username = process.argv[3];
const filePath = 'users.txt';

if (!action || !username) {
console.log('Используйте: node app.js <register|login> <username>');
process.exit(1);
}

// Функция для регистрации пользователя
function registerUser(username) {
fs.appendFile(filePath, `${username}\n`, (err) => {
if (err) {
console.error('Ошибка регистрации:', err);
process.exit(1);
}
console.log(`Пользователь ${username} зарегистрирован.`);
});
}

// Функция для входа пользователя
function loginUser(username) {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Ошибка чтения файла:', err);
process.exit(1);
}

const users = data.split('\n').map(user => user.trim());
if (users.includes(username)) {
console.log(`Пользователь ${username} успешно вошёл в систему.`);
} else {
console.log(`Пользователь ${username} не найден.`);
}
});
}

// Логика обработки команд
if (action === 'register') {
registerUser(username);
} else if (action === 'login') {
loginUser(username);
} else {
console.log('Неизвестное действие. Используйте "register" или "login".');
}

BY Node.JS [ru] | Серверный JavaScript


Share with your friend now:
tgoop.com/we_use_js/4874

View MORE
Open in Telegram


Telegram News

Date: |

Earlier, crypto enthusiasts had created a self-described “meme app” dubbed “gm” app wherein users would greet each other with “gm” or “good morning” messages. However, in September 2021, the gm app was down after a hacker reportedly gained access to the user data. In handing down the sentence yesterday, deputy judge Peter Hui Shiu-keung of the district court said that even if Ng did not post the messages, he cannot shirk responsibility as the owner and administrator of such a big group for allowing these messages that incite illegal behaviors to exist. Some Telegram Channels content management tips In the “Bear Market Screaming Therapy Group” on Telegram, members are only allowed to post voice notes of themselves screaming. Anything else will result in an instant ban from the group, which currently has about 75 members. Just at this time, Bitcoin and the broader crypto market have dropped to new 2022 lows. The Bitcoin price has tanked 10 percent dropping to $20,000. On the other hand, the altcoin space is witnessing even more brutal correction. Bitcoin has dropped nearly 60 percent year-to-date and more than 70 percent since its all-time high in November 2021.
from us


Telegram Node.JS [ru] | Серверный JavaScript
FROM American