Alperzkn
Alperzkn

Reputation: 479

Saving an array to file with nodejs and post method

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;

Upvotes: 0

Views: 837

Answers (3)

kimy82
kimy82

Reputation: 4475

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

Upvotes: 2

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

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!');
});

Upvotes: 1

boc4life
boc4life

Reputation: 961

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

Upvotes: 0

Related Questions