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

Создайте приложение на Node.js, которое принимает путь к текстовому файлу в качестве аргумента командной строки, подсчитывает количество строк, слов и символов в файле, а затем сохраняет результат в stats.json. Программа также должна уметь выводить статистику в консоль.

Программа должна уметь выводить статистику по папке в консоль и сохранять её в файл.

➡️ Пример:

node app.js report /path/to/file.txt — создает файл stats.json с количеством строк, слов и символов в файле.
node app.js print /path/to/file.txt — выводит статистику по файлу в консоль.

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

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);

const action = process.argv[2];
const filePath = process.argv[3];
const reportFile = 'stats.json';

if (!action || !filePath) {
console.log('Используйте: node app.js <report|print> <путь к файлу>');
process.exit(1);
}

async function analyzeFile(file) {
const content = await readFile(file, 'utf8');
const lines = content.split('\n').length;
const words = content.split(/\s+/).filter(Boolean).length;
const chars = content.length;

return { lines, words, chars };
}

async function generateReport(file) {
const stats = await analyzeFile(file);
fs.writeFile(reportFile, JSON.stringify(stats, null, 2), (err) => {
if (err) {
console.error('Ошибка при записи отчета:', err);
process.exit(1);
}
console.log(`Отчет сохранен в ${reportFile}`);
});
}

async function printReport(file) {
const stats = await analyzeFile(file);
console.log(`Файл: ${file}`);
console.log(`Количество строк: ${stats.lines}`);
console.log(`Количество слов: ${stats.words}`);
console.log(`Количество символов: ${stats.chars}`);
}

if (action === 'report') {
generateReport(filePath);
} else if (action === 'print') {
printReport(filePath);
} else {
console.log('Неизвестное действие. Используйте "report" или "print".');
}
Please open Telegram to view this post
VIEW IN TELEGRAM
👍2



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

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

Создайте приложение на Node.js, которое принимает путь к текстовому файлу в качестве аргумента командной строки, подсчитывает количество строк, слов и символов в файле, а затем сохраняет результат в stats.json. Программа также должна уметь выводить статистику в консоль.

Программа должна уметь выводить статистику по папке в консоль и сохранять её в файл.

➡️ Пример:

node app.js report /path/to/file.txt — создает файл stats.json с количеством строк, слов и символов в файле.
node app.js print /path/to/file.txt — выводит статистику по файлу в консоль.

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

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readFile = promisify(fs.readFile);

const action = process.argv[2];
const filePath = process.argv[3];
const reportFile = 'stats.json';

if (!action || !filePath) {
console.log('Используйте: node app.js <report|print> <путь к файлу>');
process.exit(1);
}

async function analyzeFile(file) {
const content = await readFile(file, 'utf8');
const lines = content.split('\n').length;
const words = content.split(/\s+/).filter(Boolean).length;
const chars = content.length;

return { lines, words, chars };
}

async function generateReport(file) {
const stats = await analyzeFile(file);
fs.writeFile(reportFile, JSON.stringify(stats, null, 2), (err) => {
if (err) {
console.error('Ошибка при записи отчета:', err);
process.exit(1);
}
console.log(`Отчет сохранен в ${reportFile}`);
});
}

async function printReport(file) {
const stats = await analyzeFile(file);
console.log(`Файл: ${file}`);
console.log(`Количество строк: ${stats.lines}`);
console.log(`Количество слов: ${stats.words}`);
console.log(`Количество символов: ${stats.chars}`);
}

if (action === 'report') {
generateReport(filePath);
} else if (action === 'print') {
printReport(filePath);
} else {
console.log('Неизвестное действие. Используйте "report" или "print".');
}

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


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

View MORE
Open in Telegram


Telegram News

Date: |

Deputy District Judge Peter Hui sentenced computer technician Ng Man-ho on Thursday, a month after the 27-year-old, who ran a Telegram group called SUCK Channel, was found guilty of seven charges of conspiring to incite others to commit illegal acts during the 2019 extradition bill protests and subsequent months. The group’s featured image is of a Pepe frog yelling, often referred to as the “REEEEEEE” meme. Pepe the Frog was created back in 2005 by Matt Furie and has since become an internet symbol for meme culture and “degen” culture. Other crimes that the SUCK Channel incited under Ng’s watch included using corrosive chemicals to make explosives and causing grievous bodily harm with intent. The court also found Ng responsible for calling on people to assist protesters who clashed violently with police at several universities in November 2019. The main design elements of your Telegram channel include a name, bio (brief description), and avatar. Your bio should be: 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.
from us


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