I'm making a text hosting service and I want it to say "TextMessage Not found! You can create one in the name by clicking here" but I don't know how to do that. I tried making a custom 404 error, and detecting if the file exists via the node fs module, that did not work out.
this is my code:
// Importing require packages/modules
const express = require("express");
const bodyParser = require("body-parser");
const fs = require("fs");
// Defining needed variables
const app = express();
const PORT = 3000;
// Express midleware to enable body-parser
app.use(bodyParser.urlencoded({ extended: false }));
// Express static handler
app.use(express.static("public"));
// POST API To create message/file
app.post("/api/message/submit", (req, res) => {
const file = req.body.messageText;
const fileID = req.body.messageID;
fs.writeFile(__dirname "/messageFiles/" fileID ".txt",
file, (err) => {
if (err) res.send("ERROR! <br>" err);
else res.send("Saved");
});
});
// GET API To read message/file
app.get("/message/:id", (req, res) => {
const msg = req.params.id;
if (fs.existsSync(__dirname "/messageFile/" msg ".txt")) {
res.sendFile(__dirname "/messageFiles/" msg ".txt");
} else {
res.send("Message does not exist");
}
});
// Running the server
app.listen(PORT, () => {
console.log("Running on port: " PORT);
});
`
CodePudding user response:
You may try async writing to a file by wrapping it with trycatch
block. It seems you have a problem with path to the file.
I suggest you to have a helper functions to write to a file and read from a file:
const create = async (data, fileName) => {
try {
const text = await fs.writeFile(`./files/${fileName}.txt`, data);
console.log('File write successful!');
} catch (error) {
throw new Error('File write operation failed');
}
};
const read = async (fileName) => {
try {
const fileContent = await fs.readFile(`./files/${fileName}.txt`, {encoding: 'utf-8'});
return fileContent;
} catch (error) {
throw new Error('File read operation failed');
}
};
app.post("/api/message/submit", async (req, res) => {
const fileContent = req.body.messageText;
const fileID = req.body.messageID;
const message = await create(fileContent, fileID);
message ? res.send('Successful') : res.send('Failed');
});
app.get("/message/:id", async (req, res) => {
const msgID = req.params.id;
const message = await read(msgID);
res.send(message);
});
I hope it helps!
P.S.: Don't use too many comments. Your code should be self-documenting (readable)!
P.S.S: Added async
keyword before (req, res)
.