I know that this question is many.But mine is a little hard. I'm new to fs and i wanna read a file from txt and send it to client when it gives me a GET
request and when it gives me a POST
request. Sending the request is completly fine as i checked and its using XMLHttpRequest.First of all here is my code :
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
console.log("Recieved request : " + req.method);
fs.readFileSync("chat.txt",(err,data) => {
console.log("hello");
if(req.body){
console.log("Received message : " + req.body);
var chats = data.split("\n");
if(chats.length == 40){
chats.shift();
}
chats.push(req.body);
var results = "";
for(var i in chats){
if(i == chats.length - 1){
results += chats[i];
}
else{
results += chats[i] + "\n";
}
}
fs.writeFileSync("chats.txt",results);
}
else{
console.log(data);
res.end(data.toString("utf8"));
}
});
}).listen(8080);
I think the problem is from the Sync and Async of readFile and writeFile and beside this problem, Can you say what is async
await
and promises
very summarized and simple?