【问题标题】:JavaScript/Node.JS - How to extract a value in a list of variables of a txt file to read?JavaScript/Node.JS - 如何在要读取的 txt 文件的变量列表中提取值?
【发布时间】:2020-08-30 00:23:33
【问题描述】:

我有一个包含如下变量列表的 txt 文件:

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

我只想提取我想使用 javascript 查找的变量的值(例如:查找 $VARIABLE3 的值 => VALUE3)。 有人可以帮忙吗?

在 Python 中,我找到了一种使用如下函数的方法:

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]

提前致谢。

【问题讨论】:

    标签: javascript node.js string fs readfile


    【解决方案1】:

    您可以使用readline 模块逐行读取文件。

    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
    })();
    
    

    如果您希望在找到特定变量后立即停止,您可以这样做。

    我将使用另一个使用流的线路阅读器,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
    })();
    

    【讨论】:

    • 您也可以修改此代码,以便在找到请求的值后提前停止处理数据
    • 想让 OP 做任何修改,但它是 :) @Luc125
    • @MarcosCasagrande 非常感谢,我正在寻找那个。非常感谢!
    • @MarcosCasagrande 如果您有时间和乐趣,您能否提供一个带有 readFileSync 的同步示例?不胜感激
    • 我不建议你这样做。无论如何阅读内容,使用content.split('\n') 并遍历这些行,然后使用我在'data'line 上使用的相同逻辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2018-01-11
    • 1970-01-01
    • 2016-10-24
    • 2023-03-17
    • 1970-01-01
    • 2021-02-08
    相关资源
    最近更新 更多