节点读取文件错误

时间:2017-06-09 23:58:18

标签: javascript node.js linux windows

// Basic error checking for correct number of command line arguments
if (process.argv.length < 4 || process.argv.length > 4) {
    console.log("Usage:");
    console.log("node fileToConvertFrom fileToConvertTo");
    process.exit(-1);
}

// Capture commnad line arguments. Used get filenames for reading and writing from.
var convertFrom = process.argv[2];
var convertTo = process.argv[3];

var fs = require("fs");
var importFile = fs.readFileSync("./" + convertFrom).toString('utf-8');

//var arraySeperate = text.split("<ExternalTagHere>");
var arrayByLine = importFile.split("\n");

// without manually setting index 25 to what I am searching for, and in fact what it should be already be,
// this does not work and returns index "-1" which means not found. very fucking weird.
// comment out arrayByLine[25] = "" to not have this work
// something to do with cariage returns/tabs from stupid ass fucking windows?
arrayByLine[25] = "    <ExternalTagHere>";
var getIndex = arrayByLine.indexOf("    <ExternalTagHere>");
console.log(getIndex);

//console.log(arraySeperate[0]);

//arrayEcho(arrayByMachine);

function arrayCount(arr) {
    console.log("Array count: " + arr.length);
}

function arrayEcho(arr) {
    for (var i = 0; i <= arr.length; i++) {
            console.log(arr[i]);
    }
}

因此,我导入/解析的文件是在Windows上生成的。我在命令行上带有Node的Linux机器上解析它。

当我手动设置元素时,索引25,在数组indexOf方法中成功返回。但是,当我不手动设置它时,indexOf无法找到它。这对我来说很奇怪,只是看着它们看起来完全一样的文字。所以,我认为它是Windows间距与Linux间距?还是标签?在这一点丢失了。

1 个答案:

答案 0 :(得分:0)

尝试删除\ r和\ n字符,替换

var arrayByLine = importFile.split("\n");

var arrayByLine = importFile.split("\n").map(function(s){return s.replace(/[\n\r]/g, '')});