2017-04-04 49 views
0

新增功能:更具體的描述Node.js:如何在按下提交按鈕時將公式的輸入值寫入JSON文件?

我正在編程一個網站,使用不同類型的不同產品。每個產品都有一個帶有評論功能的詳細頁面。產品詳情網站的路徑看起來像http://localhost:3000/details/type/name。當用戶填寫表單以撰寫評論並按下提交按鈕,所有的數據應被追加到產品類型的JSON文件,該文件是這樣的:

type1.json

[ 
    { 
    "name": "Product1", 
    "description": "Description1", 
    "comments":[ 
     { 
     "user": "Matthew", 
     "message": "Very Good!", 
     "timestamp": "2017-03-17T17:51Z" 
     },{ 
     "user": "Lea", 
     "message": "Nice", 
     "timestamp": "2017-03-10T13:29Z" 
     } 
    ] 
    }, 
    { 
    "name": "Product2", 
    "description": "Description2", 
    "comments":[ 
     { 
     "user": "Ann", 
     "message": "This is very useful!", 
     "timestamp": "2017-02-02T19:30Z" 
     },{ 
     "user": "Tim", 
     "message": "Awesome", 
     "timestamp": "2017-04-01T20:25Z" 
     } 
    ] 
] 

這是我的HTML文件的一部分,其中包含的形式:

details.html

<form action="" method="POST" id="commentForm"> 
    <div class="form-group"> 
     <input type="text" id="name" 
       placeholder="Name" class="form-control" name="name"/> 
    </div> 
    <div class="form-group"> 
     <textarea cols="30" rows="5" class="form-control" id="message" placeholder="Message" name="message"></textarea> 
    </div> 
    <div class="form-group"> 
     <div class="col-md-6 text-center"> 
      <button type="reset" class="btn btn-default"> 
       <span class="glyphicon glyphicon-remove"></span> 
       Reset 
      </button> 
     </div> 
     <div class="col-md-6 text-center"> 
      <button type="submit" class="btn btn-success"> 
       <span class="glyphicon glyphicon-ok"></span> 
       Send 
      </button> 
     </div> 
    </div> 
</form> 

這是我的JavaScript文件的相關部分:

details.js

$(function() { 
    $.fn.serializeObject = function() 
    { 
     var o = {}; 
     var a = this.serializeArray(); 
     $.each(a, function() { 
      if (o[this.name] !== undefined) { 
       if (!o[this.name].push) { 
        o[this.name] = [o[this.name]]; 
       } 
       o[this.name].push(this.value || ''); 
      } else { 
       o[this.name] = this.value || ''; 
      } 
     }); 
     return o; 
    }; 

    $("#commentForm").bind("submit", function(evt) { 
     console.log(JSON.stringify($("#commentForm").serializeObject())); 
     $.ajax({ 
      url: window.location.pathname, 
      type: "POST", 
      contentType: "application/json", 
      data: JSON.stringify($("#commentForm").serializeObject()), 
      success: function(data) { 
       console.log('success'); 
       console.log(JSON.stringify(data)); 
      }, 
     }); 
     return false; 
    }); 
}); 

現在的問題是:什麼在app.js寫? 以下是當前app.js的摘錄。

app.js

const express = require("express"); 
const app = express(); 
const fs = require('fs'); 
const path = require("path"); 
const jsonfile = require('jsonfile'); 
const bodyParser = require('body-parser'); 
app.use(bodyParser.json()); 

const type1File = __dirname + "/data/type1.json"; 

... 

app.post("/details/:typ/:name", function (req, res) { 
    if (req.params.typ == "type1") { 
     const apps = readJsonFile(type1File); 
     res.send(getProduct(apps, req)); 
???What to write here??? 
    } 
... 
}); 

function readJsonFile(file) { 
    try { 
     const data = fs.readFileSync(file); 
     return JSON.parse(data); 
    } catch (e) { 
     console.log(file + "could not be read. " + e); 
     return []; 
    } 
} 

我應該怎麼加?數據如何被寫入正確的JSON對象的「註釋」鍵?請幫助我,我花了很多時間嘗試不同的事情,但沒有什麼是正確的。

回答

1

注:此答案的問題被改寫之前寫的: https://stackoverflow.com/posts/43213085/revisions

這個問題太籠統,很難給你任何具體的答案。但是,如果你想在你的應用程序中持久數據,那麼你應該使用數據庫。

像Mongo,Postgres或Redis等一些數據庫需要作爲獨立的應用程序運行在相同或不同的服務器上。一些像SQLite這樣的嵌入式數據庫不需要獨立的進程,可以直接在應用程序中運行。數據庫有多種選擇,這是你必須爲你的特定情況選擇自己的東西。但是你應該選擇一些數據庫來存儲數據。

並不是不可能在更新時寫入JSON文件,然後根據需要讀取這些文件,但是必須執行的工作量才能同步對數據的訪問,以便不會有兩個請求寫同時發生,並且在寫入過程中不會發生任何讀取,所有這些都不會意外阻塞進程中的事件循環並且同時處理多個請求,這比根據預期使用任何數據庫要困難得多。

一些像Mongo這樣的數據庫可以讓你存儲任何JSON文檔(實際上它存儲了BSON,但對於用戶來說就像JSON一樣)。使用像Mongo或CouchDB這樣的文檔數據庫與使用JSON文件最相似,但使用關係數據庫也可以。幾乎每個持久數據都保存在數據庫中。如果你可以編寫你自己的數據庫來存儲JSON文件中的數據,那麼,如果你需要的話,盡一切辦法去做,但如果你不能,那麼只需使用正確的工具來完成這項工作。

話雖如此,如果你仍堅持讀寫JSON文件,這裏是做什麼:

要寫入數據作爲JSON到文件中,您將需要使用JSON.stringify()fs.writeFile()

要從文件中讀取JSON數據,您需要使用fs.readFile()JSON.parse()

事情要記住:

  1. JSON.parse()JSON.stringify()必須始終包裹在try/catch塊或否則你的應用程序會崩潰(或使用tryjson模塊從NPM)。
  2. 切勿使用名稱中帶有「同步」的fs模塊的方法,否則您的應用將被阻止服務請求。
  3. 您需要實現對文件訪問的鎖定和同步,否則您的數據將被破壞 - 這是最困難和最重要的部分,這就是人們爲什麼要使用數據庫的原因。
+0

感謝您的回答!我應該如何寫出表單數據將寫入JSON文件中正確的「註釋」鍵? – LCP