Search code examples
javascriptnode.jsstringfsreadfile

JavaScript/Node.JS - How to extract a value in a list of variables of a txt file to read?


I've a txt file with a list of variables like this:

$VARIABLE1 = 'VALUE1';
$VARIABLE2 = 'VALUE2';
$VARIABLE3 = 'VALUE3';
$VARIABLE4 = 'VALUE4';

I'd like to exctract only the value of the variable I want find using javascript (example: find value of $VARIABLE3 => VALUE3). Someone can help?

In Python I found a way using a function like this:

def findValue():
    import re
    valueToFind = []
    lineNum = 0
    pattern = re.compile("string to find", re.IGNORECASE)
    with open(FILE_PATH, 'rt') as myFile:
        for line in myFile:
            lineNum += 1
            if pattern.search(line) is not None:
                valueToFind.append((lineNum, line.rstrip('\n')))
    for find in valueToFind:
        string = find[1].split("'")
        return string[1]

Thanks in advance.


Solution

  • You can use readline module to read a file line by line.

    const fs = require('fs');
    const readline = require('readline');
    const { once } = require('events');
    
    
    async function getVariables(file) {
        const stream = fs.createReadStream(file);
        const lineReader = readline.createInterface({
            input: stream
        })
    
        const variables = {};
        lineReader.on('line', line =>  {
            const [key, value] = line.split('=').map(item => item.trim())
            variables[key] = value.split("'")[1];
        })
    
        // wait until the whole file is read
        await once(stream, 'end');
    
        return variables;
    }
    
    (async() => {
       const variables = await getVariables('./file.txt')
       console.log(variables['$VARIABLE4']) // VALUE4
    })();
    
    

    If you prefer to just stop once you find a specific variable, you can do so.

    I'll use an alternative line reader using streams, with split2

    const split2 = require('split2');
    
    async function findVariable(file, variable) {
        const stream = fs.createReadStream(file, { highWaterMark: 5 } );
        const lineReader = stream.pipe(split2())
    
        let result = null;
        lineReader.on('data', async function (line) {
          const [key, value] = line.split('=').map(item => item.trim())
          if(key === variable) {
            result = value.split("'")[1];
            stream.destroy();
          }
        })
    
        // wait until the whole file is closed
        await once(stream, 'close');
        return result;
    }
    
    (async() => {
       const value4 = await findVariable('./file.txt', '$VARIABLE4')
       // null if not found
       console.log(value4) // VALUE4
    })();