javascript - 使用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;
解决方案
当您使用 fs 写入文件时,您正在传递您的 todos,它是一个对象数组。这就是您看到[object Object]的原因。尝试将数组发送到函数JSON.stringify(todos)并使用将是字符串的输出。
希望能帮助到你
推荐阅读
- python - Pandas Python:使用逗号千位分隔符打印所有相关列的单行器?
- user-input - 我不明白为什么 JS 不收集用户输入
- python - Python,在制作第二个数组
- angular - 无法读取 null 的属性“setValue” - Angular
- shell - 在 Shell/awk/sed 中除最后一个大括号外的每个大括号都添加一个逗号
- python - NameError:名称未定义(仅适用于测试用例 2)
- python - 使用多对多关系时,Flask-SQLAlchemy 在查询中返回对象
- react-native - 按钮样式在本机反应中不起作用
- pandas - 条形图上看不到重复项
- mutt - 配置neomutt的索引格式