我正在使用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) 并使用输出(将是一个字符串)。
希望对你有帮助
关于javascript - 使用nodejs和post方法将数组保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57094893/