读取node.js中的文件文本时,没有解释逃生字符



在从文件中读取字符串时,逃脱字符没有被解释

文件内容:" Hello world r n ttesting r n tlastline r tthank You"

var file = fs.readFileSync('./file.txt','utf-8');
console.log(file);
//Output
Hello worldrntTestingrntlastlinertthank you

与Console.log((

一起使用的同一字符串
console.log("Hello worldrn        Testingrn    lastlinerthank you");
//output        
Hello world
    Testing
    thank you

我发现了类似的问题,但没有解决我的问题或接受回答

readFileSync()函数不知道您的文件包含特殊的元字符,它将返回原始数据。

可以自己转换数据:

function unbackslash(s) {
    return s.replace(/\([\rnt'"])/g, function(match, p1) {
        if (p1 === 'n') return 'n';
        if (p1 === 'r') return 'r';
        if (p1 === 't') return 't';
        if (p1 === '\') return '\';
        return p1;       // unrecognised escape
    });
}

不幸的是,仅返回'' + p1是不可能的,因为只有完整的字符串文字可能会逃脱。

尝试以下:

function parseString(str) {
    return str.replace(/\r/g, 'r').replace(/\n/g, 'n').replace(/\t/g, 't')
}
var file = fs.readFileSync('./file.txt', 'utf-8')
file = parseString(file)
console.log(file)

最新更新