Reputation: 1287
When reading a file line by line with below code. It seems to not read the string correctly?
Part of the String on each line in file is this:
b53pd4574z8pe9x793go
console.log(pathcreatefile) correctly shows:
b53pd4574z8pe9x793go
But is seems that: fs.promises.writeFile does this?:
b53'd4574z8pe9x793go
Console error is this:
(node:1148) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open 'C:\myproject\instances\b53'd4574z8pe9x793go\folder\testA.txt
My code is the below. I have added the 3 lines I read from the file in the code:
'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)
})()
Upvotes: 4
Views: 388
Reputation: 2502
There is no need to wrap fs.promises.writeFile into an extra Promise, it returns Promise without any wrappers.
Also you should the constant from 'os' package for line separator to make it work across different operating systems. The following code will work for you:
'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")
}
}));
})()
Upvotes: 2