首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从文件中读取行不能用fs.readFileSync返回正确的字符串

从文件中读取行不能用fs.readFileSync返回正确的字符串
EN

Stack Overflow用户
提问于 2019-03-05 13:22:17
回答 1查看 261关注 0票数 4

用下面的代码逐行读取文件时。它似乎没有正确地读取字符串?

文件中每一行的字符串的一部分如下:

b53pd4574z8pe9x793go

Console.log(路径创建文件)正确显示:

b53pd4574z8pe9x793go

但似乎是这样的: fs.promises.writeFile会这么做吗?

b53'd4574z8pe9x793go

控制台错误是:

'C:\myproject\instances\b53'd4574z8pe9x793go\folder\testA.txt:(节点:1148) UnhandledPromiseRejectionWarning:错误: ENOENT:没有这样的文件或目录,打开UnhandledPromiseRejectionWarning

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

代码语言:javascript
复制
'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)
    })()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-05 13:56:04

没有必要将fs.promises.writeFile包装成额外的承诺,它返回的承诺没有任何包装。

此外,您还应该为行分隔符使用“os”包中的常量,以使其在不同的操作系统中工作。以下代码适用于您:

代码语言:javascript
复制
         '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")
        }
    }));
})()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55003881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档