从文件读取行不会返回带有fs.readFileSync的正确字符串

问题描述 投票:3回答:1

使用以下代码逐行读取文件时。好像没有正确读取字符串?

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

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

但似乎是:fs.promises.writeFile这样做?: b53'd4574z8pe9x793go

控制台错误是这样的: (node:1148)UnhandledPromiseRejectionWarning:错误: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)
    })()
javascript node.js readfile
1个回答
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")
        }
    }));
})()
© www.soinside.com 2019 - 2024. All rights reserved.