簡體   English   中英

將新的 object 添加到數組中到 nodeJS 中的 js 文件中

[英]add new object into a array to a js file in nodeJS

我只是想知道如何通過快速路由器端點將數據添加(推送)到數組中。 假設我在data/data.js目錄中有一個數組,我的路由器代碼如下所示:

const express = require('express');
const bodyParser = require('body-parser');
const productRouter = express.Router();
//! bring data
const { products } = require('../data/data');
productRouter.use(bodyParser.json());

productRouter
  .route('/')
  .post((req, res, next) => {
    if (req.body !== null) {
     //some logic
      } else {
        products.push(req.body);
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json(products);
      }
    } else {
      //handle error
    }
  });
module.exports = productRouter;

當我在路由的端點中涉及 POST 方法時,它會推送新數據並使用更新的數組進行響應。 但是當我檢查我的快速文件時,它仍然是舊數組。 為什么我丟失了數據?
如果有人幫助我解決這個問題,我衷心感謝。


正如@Aditya toke 和@Andre Nuechter 建議的那樣,我像這樣更新我的代碼:

exports.products = [
  {
    title: 'camera',
    imageUrl: 'https://source.unsplash.com/gGgoDJRD2WM/300x300',
    id: 1,
  },
...
]
exports.orders = [];
{"title":"mens","imageUrl":"https://source.unsplash.com/1-nx1QR5dTE/300x300","id":"6"}

但它會像這樣推送新數據:

 exports.products = [ { title: 'camera', imageUrl: 'https://source.unsplash.com/gGgoDJRD2WM/300x300', id: 1, }, ... ] exports.orders = []; {"title":"mens","imageUrl":"https://source.unsplash.com/1-nx1QR5dTE/300x300","id":"6"}

這不是我想要的。 有沒有辦法將它添加到產品數組中? 還是有更好的方法?

數據丟失,因為 push 不會更改磁盤上的文件。 為此,您需要使用fs.writeFile類的東西。

正如您提到的在文件中保存數據,這只能通過使用文件系統在文件中寫入數據來實現,
我建議使用 JSON 擴展文件,因為它易於解析和閱讀。
您必須使用文件系統在文件中寫入數據。
並且進一步添加它可以用作整個項目的全局變量。
有多種方法可以使用 node js 來玩文件系統。
https://nodejs.org/api/fs.html

更新了答案

@falamiw 請按照以下步驟操作
1.不要使用data.js 開始使用data.json
data.json 內部的結構將是這樣的

{
products : [
  {"title":"mens","imageUrl":"https://source.unsplash.com/1-nx1QR5dTE/300x300","id":"6"},
  {"title":"women","imageUrl":"https://source.unsplash.com/1-nx1QR5dTE/300x300","id":"7"}
          ]
}

在此 JSON 文件中進行更改的代碼

 const fs = require('fs');
    let rawdata = fs.readFileSync('data.json');
   let productArray = JSON.parse(rawdata);
  // push changes to your array
   productArray ['product'].push({ any thing you want to add })
  1. 在將 object 推入數組后,現在我們將使用文件系統對 data.json 文件進行更改。

     let data = JSON.stringify(productArray ); fs.writeFileSync('data.json', data);

就是這樣,現在您可以看到文件中的更改。 我沒有測試過這段代碼,但我相信它只會讓你調試和檢查它的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM