使用Node.js和Post方法将数组保存到文件

时间:2019-07-18 12:51:15

标签: javascript node.js ejs fs

我正在使用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;

3 个答案:

答案 0 :(得分:2)

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

希望有帮助

答案 1 :(得分:1)

使用JSON.stringify转换为字符串

fs.writeFile('todo.txt', JSON.stringify(todos), (err) => {
        if (err) console.log(err);
      console.log('Successfuly written to the file!');
});

答案 2 :(得分:0)

您是否尝试过以某种方式破坏数组?我认为您遇到的问题与传递给fs.writeFile()的数据类型有关。 node.js文档说,data参数可以采用String,Buffer,TypedArray或DataView的形式。

有关更多信息,请https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback