NodeJS \ JS чтение файлов.

Поддержка
  • BAS настолько особенный, что без опознавания https://wiki.bablosoft.com/doku.php?id=node.js писать что либо вообще походу без ошибок не возможно. Однако и после изучения статьи с переводчиком, я так ни черта и не понял.

    const fs = require('fs').promises;
    const path = require('path');
    
    const FILE_LIST = [[FILE_SEARCH_RESULT]]
    
    async function readFiles(filePaths) {
        const newList = [];
        for (const filePath of filePaths) {
            try {
                const content = await fs.readFile(filePath, 'utf8');
                newList.push(content);
            } catch (error) {
                console.error(`Ошибка при чтении файла ${filePath}:`, error);
            }
        }
        [[NEW_LIST]] = NEW_LIST;
        return newList;
    }
    
    readFiles(FILE_LIST).then(newList => {
        console.log('Содержимое файлов:', newList);
    }).catch(error => {
        console.error('Ошибка при чтении файлов:', error);
    });
    
  • @Kinokio

    Работоспособность кода не проверял.

    const fs = require('fs').promises;
    const path = require('path');
    
    const fileList = [[FILE_SEARCH_RESULT]];
    
    async function readFiles(filePaths) {
        const newList = [];
        for (const filePath of filePaths) {
            try {
                const content = await fs.readFile(filePath, 'utf8');
                newList.push(content);
            } catch (error) {
                console.error(`Error reading file ${filePath}:`, error);
            }
        }
        return newList; // Returning the newList
    }
    
    (async function () {
        await (new Promise((resolve, reject) => {
            readFiles(fileList).then(newList => {
                console.log('File contents:', newList);
                resolve(); // <==== HERE <=======
            }).catch(error => {
                console.error('Error reading files:', error);
                reject(); // Correctly rejecting the promise
            });
        }));
    })();
    
  • @sergerdn Переменная NEW_LIST пуста. Даже после того как я изменил код.

    const fs = require('fs').promises;
    const path = require('path');
    
    const fileList = [[FILE_SEARCH_RESULT]];
    
    async function readFiles(filePaths) {
        const newList = [];
        for (const filePath of filePaths) {
            try {
                const content = await fs.readFile(filePath, 'utf8');
                newList.push(content);
            } catch (error) {
                console.error(`Error reading file ${filePath}:`, error);
            }
        }
        [[NEW_LIST]] = newList;
        return newList; // Returning the newList
    }
    
    (async function () {
        await (new Promise((resolve, reject) => {
            readFiles(fileList).then(newList => {
                console.log('File contents:', newList);
                resolve(); // <==== HERE <=======
            }).catch(error => {
                console.error('Error reading files:', error);
                reject(); // Correctly rejecting the promise
            });
        }));
    })();
    
  • @Kinokio said in NodeJS \ JS чтение файлов.:

    @sergerdn Переменная NEW_LIST пуста. Даже после того как я изменил код.

    Не вникал в код. Может быть ошибка в изначальном коде была совсем не одна.

  • В целом я готов заплатить за решение разумные деньги
    Лол, задача то простая.
    Есть список, каждая строка в нём - путь к файлу.
    Мне нужно прочитать этот файл и положить содержимое в список.
    И так каждую строку из первого списка.

  • const fs = require('fs').promises;
    const path = require('path');
    
    const FILE_LIST = [[FILE_SEARCH_RESULT]]
    
    async function readFiles(filePaths) {
        const newList = [];
        for (const filePath of filePaths) {
            try {
                const content = await fs.readFile(filePath, 'utf8');
                newList.push(content);
            } catch (error) {
                console.error(`Ошибка при чтении файла ${filePath}:`, error);
            }
        }
        return newList;
    }
    
    await(new Promise((resolve, reject) => {
        readFiles(FILE_LIST).then(newList => {
            console.log('Содержимое файлов: ' +  newList);
            [[NEW_LIST]] = newList
            resolve()
        }).catch(error => {
            console.error('Ошибка при чтении файлов:', error);
            reject(error)   
    });
    }));