Exercices CM 1
This commit is contained in:
69
exercice4.js
Normal file
69
exercice4.js
Normal file
@@ -0,0 +1,69 @@
|
||||
function readFile(path, charset) {
|
||||
throw new Error("Function not implemented.");
|
||||
}
|
||||
|
||||
function readTextFileIfExists(path) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!path) {
|
||||
reject(new Error("No file path provided"));
|
||||
return;
|
||||
}
|
||||
|
||||
readFile(path, "utf8")
|
||||
.then(data => {
|
||||
if (data.length === 0) {
|
||||
reject(new Error("File is empty")); // explicit failure
|
||||
} else {
|
||||
resolve(data); // successful read
|
||||
}
|
||||
})
|
||||
.catch(err => reject(err)); // I/O error
|
||||
});
|
||||
}
|
||||
|
||||
readTextFileIfExists("data.txt")
|
||||
.then(text => console.log("File contents:", text))
|
||||
.catch(err => console.error("I/O error:", err.message));
|
||||
|
||||
try {
|
||||
const text = await readTextFileIfExists("data.txt");
|
||||
console.log("File contents:", text);
|
||||
} catch (err) {
|
||||
console.error("I/O error:", err.message);
|
||||
}
|
||||
|
||||
const files = ["file1.txt", "file2.txt", "file3.txt"];
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const text = await readTextFileIfExists(file);
|
||||
console.log("File contents:", text);
|
||||
} catch (err) {
|
||||
console.error("I/O error:", err.message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const otherFiles = ["does_not_exist.txt", "file2.txt", "file3.txt"];
|
||||
|
||||
const failContents = await Promise.all(
|
||||
otherFiles.map(readTextFileIfExists)
|
||||
);
|
||||
try {
|
||||
failContents.forEach((text, i) => {
|
||||
console.log("File contents:", text);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("I/O error:", err.message);
|
||||
}
|
||||
|
||||
const successContents = await Promise.allSettled(
|
||||
files.map(readTextFileIfExists)
|
||||
);
|
||||
successContents.forEach((result, i) => {
|
||||
if (result.status === "fulfilled") {
|
||||
console.log("File contents:", result.value);
|
||||
} else if (result.status === "rejected") {
|
||||
console.error("I/O error:", result.reason);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user