0

I am using ejs and nodejs. Trying to post an array to a file. I can visualize and get the array in ejs file so it is ok to show on the page but when I try to save in a file, it return [object Object] in file. But I can see the values in array.

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 Answers 3

2

When you are writing to a file using fs you are passing your todos which is an Array of Object. This is why you see [object Object]. Try to send the array to the function JSON.stringify(todos) and use the output which will be a string.

Hope it helps

Sign up to request clarification or add additional context in comments.

Comments

1

use JSON.stringify to convert in string

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

Comments

0

Have you tried destructuring the array somehow? I believe that the issue you're having is related to the data type you're passing into the fs.writeFile(). The node.js documentation says that the data parameter can be in the form of a String, Buffer, TypedArray, or DataView.

For more information, https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.