用下面的代码逐行读取文件时。它似乎没有正确地读取字符串?
文件中每一行的字符串的一部分如下:
b53pd4574z8pe9x793go
Console.log(路径创建文件)正确显示:
b53pd4574z8pe9x793go
但似乎是这样的: fs.promises.writeFile会这么做吗?
b53'd4574z8pe9x793go
控制台错误是:
'C:\myproject\instances\b53'd4574z8pe9x793go\folder\testA.txt:(节点:1148) UnhandledPromiseRejectionWarning:错误: ENOENT:没有这样的文件或目录,打开UnhandledPromiseRejectionWarning
我的代码如下。我在代码中添加了从文件中读取的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)
})()发布于 2019-03-05 13:56:04
没有必要将fs.promises.writeFile包装成额外的承诺,它返回的承诺没有任何包装。
此外,您还应该为行分隔符使用“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")
}
}));
})()https://stackoverflow.com/questions/55003881
复制相似问题