B
B
Brendan Castaneda2021-08-01 23:02:27
Node.js
Brendan Castaneda, 2021-08-01 23:02:27

How to convert a string in a text file to an object?

How can I convert a string @import 'vars';to an object?
Those. @importthis will be the key
And varsthis will be the value
Something like this should work. I am reading a text file, I find several values ​​​​of them and I want to convert them to objects. But I can't figure out exactly how to do it.let a = { @import: 'vars' }
@import

const fs = require('fs');
const log = console.log;

if (data.indexOf('@import') >= 0) { // Если файл содержит в себе @import тогда
    // let a = str.split(';')[0]; // Получем значение до знака ;
    // let b = file.contents.split('@import')[1]; // Получем значение после @import
    // let value = JSON.parse
    // let obj = '@import' [value]
    // let object = obj.split(separator)
    fs.readFile(file.path, "utf8",
        function(error, data) {
            if (error) throw error;
            if (data.indexOf('@import') >= 0) {
                log('===============' + data)
            }
        });
} else {
    log('error file is not a @import')
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Brendan Castaneda, 2021-08-04
@ae_ph

I did this with a regular expression match.
file - The file.
file.path - The path to the file.
I pass the file to the function...
Next, I read fs.readFile the files I need from file.path using nodejs methods. I
create a do...while loop with a condition.
In the condition, I compare the read file by a regular expression and at the end add the resulting values ​​to the array.
Components reg. expressions:

@import - literally this sequence of characters
\s+ - at least one whitespace character
["'] - exactly one quote character (either " or ')
([^"']+) - capturing (in the first group) any characters except " and ', at least one such "non-quote" character
The quantifier + ("one or more") is greedy by default, so the maximum possible number of "non-quote" characters of the input string gets into the result capturing group. Similarly with spaces: with the given quantifier, the \s token will match as many whitespace characters as possible.
The final part of the expression ["'];optional, will work without it: this part is added to the example only for a better understanding of regex (with this part, the expression completely describes the statement with the @import directive ).

const fs = require('fs');
const log = console.log;

fs.readFile(file.path, "utf8", (err, elem) => {
    if (err) throw err;
    log('element' + elem) // Содержимое файлов которые я прочитывал.
    let result;
    do {
        const regexp = /@import\s*["']([^"']+)["'];/gi; // Регулярное выражение 
        let result = elem.matchAll(regexp); // Метод str.matchAll(regexp) используется, для поиска всех совпадений вместе со скобочными группами.

        // получение массива строк со значениями из первой группы рег.выражения:
        const matchGroupValues = [...result].map(([, group1]) => group1);
        log(matchGroupValues); // [ 'vars', 'dwada', 'global' ] 
        // оборачивание полученных значений в массивы:
        const valuesInArrays = matchGroupValues.map(value => [value]);
        log(valuesInArrays); // [ [ 'vars' ], [ 'dwada' ], [ 'global' ] ]
        for (let value of valuesInArrays) {
            file.stem = value;
            // log('----------------' + value.join())
            log('----------------' + file.stem) // Имена файлов равны импортам (@import name)
        }
    } while (result >= 0);
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question