从文件读取行无法使用fs.readFileSync返回正确的字符串

时间:2019-03-05 13:22:17

标签: javascript node.js readfile

使用以下代码逐行读取文件时。似乎无法正确读取字符串?

文件中每一行的部分字符串是这样的:
b53pd4574z8pe9x793go

console.log(pathcreatefile)正确显示:
b53pd4574z8pe9x793go

但是似乎:fs.promises.writeFile可以做到这一点?:
b53'd4574z8pe9x793go

控制台错误是这样的:
(节点:1148)UnhandledPromiseRejection警告:错误:ENOENT:没有此类文件或目录,请打开“ C:\ myproject \ instances \ b53'd4574z8pe9x793go \ folder \ testA.txt

我的代码如下。我在代码中添加了从文件中读取的3行:

'use strict';
const fs = require('fs');
var i;


//1|one/a|test1|C:/myproject/instances/b53pd4574z8pe9x793go/folder/testA.txt
//1|two/b|test2|C:/myproject/instances/b53pd4574z8pe9x793go/folder/testB.txt
//1|three/c|test3|C:/myproject/instances/b53pd4574z8pe9x793go/folder/testC.txt
var textarray = fs.readFileSync("C:/myproject/folder/testfile.txt").toString('utf-8').split("\n"); //Read the file


(async () => {
    var thePromises = []
    for (i = 0; i < textarray.length; i++) {

        //1|one/a|test1|C:/myproject/instances/b53pd4574z8pe9x793go/folder/testA.txt
        const line = textarray[i].split("|")
        if (line.length == 4) {

            const pathcreatefile = line[3] //C:/myproject/instances/b53pd4574z8pe9x793go/folder/testA.txt
            console.log(pathcreatefile)

            try {
                    let tickerProcessing = new Promise(async (resolve) => {
                    await fs.promises.writeFile(pathcreatefile, "hello")
                    resolve()
                })
                thePromises.push(tickerProcessing)

            } catch (e) {
                console.error(e)
            }
        }
    }

    // wait for all of them to execute or fail
    await Promise.all(thePromises)
    })()

1 个答案:

答案 0 :(得分:1)

无需将fs.promises.writeFile包装到一个额外的Promise中,它会返回Promise而没有任何包装。

此外,您还应该使用'os'包中的常量作为行分隔符,以使其能够在不同的操作系统上运行。 以下代码将为您工作:

         'use strict';
var endOfLine = require('os').EOL;
const fs = require('fs');
var textarray = fs.readFileSync("./testfile.txt").toString('utf-8').split(endOfLine);
(async () => {
    await Promise.all(textarray.map((textElement) => {
        const line = textElement.split("|")
        if (line.length === 4) {
            const pathcreatefile = line[3] 
            console.log(pathcreatefile)
            return fs.promises.writeFile(pathcreatefile, "hello")
        }
    }));
})()