node. JS Development----Message Board instance FS read-write file

Source: Internet
Author: User

The project structure is as follows:

App.js

CONST EXP = require (' Express '), Bodyparser = require (' Body-parser '), FS = require (' FS '), Multer = require ('            Multer '), APP = exp (), multipart = Multer (); The method used to create the object as above exp ()/multer ()//can be called Factory method App.use (exp.static (' static ')) App.use (bodyparser.urlencoded ()) App.post      ('/add ', Multipart.array (), (req, res) = {Console.log (Multipart.array ());           Content message Contents var = req.body.content//message is a JSON data format var message = {content:content,            Time:new Date (), ip:req.ip};              Asynchronously determines whether the file exists fs.exists (' data ', (exists) = {if (!exists) {///If the file does not exist, the file is created synchronously          The subsequent code fs.mkdirsync (' data ') will not continue until the file is created successfully.                  } fs.appendfile (' Data/message.txt ', json.stringify (message) + ', ', (error) = = {if (error) {       %s is called placeholder Console.error (' Error saving file:%s ', error '}   })})//file suffix determines what icon the operating system uses to display files//determine what program the operating system uses to open files//AppendFile can append data to the end of the file//if the file Does not exist, it automatically creates files//determines whether a file or folder exists Fs.exists//Create folder Fs.mkdir//delete file Fs.unlink//delete folder Fs.rmdir must is an empty folder to delete//Read file Fs.readfile res.status. JSON ({message: ' Thank you for your message! })//App.get ('/messages ', (req, res) = {fs.exists (' Data/message.txt ', (exists) + = {if (                      exists) {fs.readfile (' data/message.txt ', (error, data) = {if (!error) {                      var result = ' [' + data;                      result = Result.substr (0, result.length-1);                      result = result + '] ';                      Console.log (result);                  Res.status. Send (Result);          }})} else {res.status). Send (' [] '); })}) App.listen (+, () = Console.log (' Server RunninG.. '));   

 

Add.html

<! DOCTYPE html>  

  

Index.js

var xhr = new XMLHttpRequest () Xhr.onreadystatechange = function () {if (xhr.readystate = = 4) {//Responset          Ext Response Text Console.log (xhr.responsetext);          var arr = json.parse (Xhr.responsetext);          Arr array Console.log (arr);          var messages = ';                            Reverse loop an array so that the latest message appears at the top for (var i = arr.length-1; i >-1; i--) {var message = Arr[i]; Use DOM to add message data to page//var box = document.createelement (' div ')//Document.body . appendchild (box)//var content = document.createelement (' P ')//Content.innertex t = message.content//box.appendchild (content)//var time = Document.createeleme                            NT (' span ')//Time.innertext = FormatDateTime (new Date (Message.time))//Box.appendchild (time)         var ip = document.createelement (' span ')     Ip.innertext = Formatip (MESSAGE.IP)//Box.appendchild (IP)//using a spelling string method to the page Add message messages + = ' <section> ' messages + = ' <p> ' Messages + = Message.cont ENT messages + = ' </p> ' messages + = ' <span> ' Messages + = FormatDateTime (              New Date (Message.time));              Messages + = ' </span> ' messages + = ' <span> ' Messages + formatip (MESSAGE.IP); Messages + = ' </span> ' messages + = ' </section> '} document.quer Yselector (' article '). InnerHTML = Messages}} xhr.open (' GET ', ' Messages ') Xhr.send () function FormatDateTime (                    T) {var m = t.getmonth () + 1, d = t.getdate (), H = t.gethours (), M = T.getminutes () JS is case-sensitive! So you can use M, m to represent two different variables m = m < 10? ' 0 ' + m:m d = d < 10? ' 0' + d:d H = h < 10? ' 0 ' + h:h m = m < 10? ' 0 ' + m:m return t.getfullyear () + '-' + M + '-' + D + ' + H + ': ' + m} function Formatip (IP) {if (Ip.startswith (':: 1 '))   {return ' 127.0.0.1 '} if (Ip.startswith (':: FFFF: ')} {return Ip.substr (7)}}

 

The final data is stored in JSON format in Message.txt



node. JS Development----Message Board instance FS read-write file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.