困惑在节点js中获取值

时间:2017-11-06 17:56:08

标签: javascript node.js

我正在编写节点js代码来执行以下操作。

  1. 逐行阅读文件
  2. 查找正则表达式匹配并分配给变量
  3. 在以下匹配中使用此值。
  4. 以下是我正在使用的代码。

    const fs = require('fs');
    const readline = require('readline');
    
    const readFile = readline.createInterface({
        input: fs.createReadStream('./readFile.txt'),
        output: fs.createWriteStream('./writeTxt.txt'),
        terminal: false
    });
    
    readFile
        .on('line', transform)
        .on('close', function () {
            console.log(`Created "${this.output.path}"`);
        });
    
    function transform(line) {
        var stringToReplace;
        var string = line;
        var re = new RegExp("^<lsec uid='(.*)' d='(.*)' n='' anchor='(.*)'>$");
        var re1 = new RegExp("^<lsbsec d='(.*)' sbsecloc='(.*)' sbsecanchor='(.*)'>$");
        if (re.test(string)) {
            stringToReplace = string.replace(/<lsec uid='(.*)' d='(.*)' n='' anchor='(.*)>/g, "$1")
            console.log(stringToReplace);
        } else if (re1.test(string)) {
            console.log(stringToReplace)
        }
        else {
            console.log("Invalid");
        }
    
    }
    

    ,我得到的输出是

    Invalid
    Invalid
    Invalid
    undefined
    Invalid
    Invalid
    2
    Invalid
    Invalid
    undefined
    Invalid
    Invalid
    3
    Invalid
    Invalid
    undefined
    Invalid
    Invalid
    

    但我期待的输出而不是undefinedNumber应该在那里。

    这是我的文本文件。

    <lsec uid='1' d='1' n='' anchor='1'> = > 1
    <name>Normal Text</name> 
    <p>Normal Text
    <lsbsec d='1' sbsecloc='(1)' sbsecanchor='(1)'>
    <p>Normat Text</lsbsec>
    </lsec>
    <lsec uid='2' d='2' n='' anchor='2'>
    <name>Normal Text</name>
    <p>Normal Text
    <lsbsec d='1' sbsecloc='(1)' sbsecanchor='(1)'>
    <p>Normat Text</lsbsec>
    </lsec>
    <lsec uid='3' d='2' n='' anchor='2'>
    <name>Normal Text</name>
    <p>Normal Text
    <lsbsec d='1' sbsecloc='(1)' sbsecanchor='(1)'>
    <p>Normat Text</lsbsec>
    </lsec>
    

    这非常令人困惑。

    请让我知道我哪里出错了,我该如何解决这个问题。

    由于

2 个答案:

答案 0 :(得分:0)

您没有在else中设置stringToReplace的值,如果。

答案 1 :(得分:0)

未定义的值未定义

else if (re1.test(string)) {
        console.log(stringToReplace)
    }

此处stringToReplace未定义,因为之前未为其分配任何值。

可能是你想:

else if (re1.test(string)) {
        //same expression as in if
        stringToReplace = string.replace(/<lsec uid='(.*)' d='(.*)' n='' anchor='(.*)>/g, "$1")
        console.log(stringToReplace)
    }

编辑(基于评论):

if (re.test(string) || re1.test(string)) {
        stringToReplace = string.replace(/<lsec uid='(.*)' d='(.*)' n='' anchor='(.*)>/g, "$1")
        console.log(stringToReplace);
}