code
import express from "express";
import fs from "fs";
import fsAsync from "fs/promises";
const app = express();
app.use(express.json());
app.get("/file1", (req, res) => {
fs.readFile("./file1.txt", (err, data) => {
if (err) {
res.status(404).send("file1.txt NOT FOUND");
} else {
const text = data.toString();
res.send(text);
}
});
});
app.get("/file2", (req, res) => {
fsAsync
.readFile("./file2.txt")
.then((data) => {
const text = data.toString();
res.send(text);
})
.catch((err) => {
res.status(404).send("file2.txt NOT FOUND");
});
});
app.get("/file3", async (req, res) => {
try {
const data = await fsAsync.readFile("./file3.txt");
const text = data.toString();
res.send(text);
} catch (error) {
res.status(404).send("file3.txt NOT FOUND");
}
});
app.use((error, req, res, next) => {
console.error(error);
res.status(500).json({ message: "ERROR" });
});
app.listen(8000);
file1.txt
가 없을 때
![](https://velog.velcdn.com/images/fkstndnjs/post/811db5cf-7958-4a0f-a151-b2f90bba3f9c/image.png)
file1.txt
가 있을 때 (file1.txt 안의 내용이 출력된다)
![](https://velog.velcdn.com/images/fkstndnjs/post/49426cae-d1a6-4dc5-bf0b-e741548ae38b/image.png)
file2.txt
가 없을 때
![](https://velog.velcdn.com/images/fkstndnjs/post/35040664-8629-44b5-9eae-37b9797ed52c/image.png)
file2.txt
가 있을 때
![](https://velog.velcdn.com/images/fkstndnjs/post/0c5a9e69-ee33-4349-86c0-205f9849ffa2/image.png)
file3.txt
가 없을 때
![](https://velog.velcdn.com/images/fkstndnjs/post/ca9f76bd-600e-499e-b6b6-f5be366694c6/image.png)
file3.txt
가 있을 때
![](https://velog.velcdn.com/images/fkstndnjs/post/f566ee1c-b0e5-45ad-bad1-368ac03fe3f2/image.png)