首页 > 解决方案 > 使用nodejs和post方法将数组保存到文件

问题描述

我正在使用 ejs 和 nodejs。试图将数组发布到文件中。我可以在 ejs 文件中可视化并获取数组,因此可以在页面上显示,但是当我尝试保存在文件中时,它会在文件中返回 [object Object]。但我可以看到数组中的值。

const express = require('express');
const router = express.Router();
const fs = require('fs');

const todos = [];
const file = 'ToDox.txt'
// /admin/add-product => GET
router.get('/', (req, res, next) => {
  res.render('index', { pageTitle: 'Add ToDo Page'});
});

// /admin/add-product => POST
router.post('/', (req, res, next) => {
  todos.push({ title: req.body.title, description: req.body.description});
  res.redirect('/todos');
  console.log(todos);
  fs.writeFile(file, todos, (err) => {
      if (err) console.log(err);
    console.log('Successfuly written to the file!');
  })
});

exports.routes = router;
exports.todos = todos;

标签: javascriptnode.jsejsfs

解决方案


当您使用 fs 写入文件时,您正在传递您的 todos,它是一个对象数组。这就是您看到[object Object]的原因。尝试将数组发送到函数JSON.stringify(todos)并使用将是字符串的输出。

希望能帮助到你


推荐阅读