miro
miro

Reputation: 19

Output gives me [object Object]

I'm looking for the answer my problem - my output is wrong and I don't know what exactly is incorrect. Maybe some part of code is missing, I really don't know - I still learning.

I use node.js (v10.15.3) and I only want to display console.log output to txt file.

My output exported to txt file should display like below:

[ Card { suit: 'Clubs', value: 3 },   
  Card { suit: 'Clubs', value: 8 },
  Card { suit: 'Diamonds', value: 9 },
  Card { suit: 'Hearts', value: 5 },
  Card { suit: 'Clubs', value: 10 } ]

but in received text file I gets

[object Object],[object Object],[object Object],[object Object],[object Object]

Below is my code:

console.log = function(msg) {
    fs.appendFile("OutputTask2and3.txt", msg, function(err) {
        if(err) {
          throw err;
        }
    });
}

class Card {
  constructor(suit, value) {
    this.suit = suit;
    this.value = value;
  }
}

class Deck {
  constructor() {
    this.deck = [];
  }

  createDeck(suits, values) {
    for (let suit of suits) {
      for (let value of values) {
        this.deck.push(new Card(suit, value));
      }
    }
    return this.deck;
  }

  shuffle() {
    let counter = this.deck.length,
      temp,
      i;

    while (counter) {
      i = Math.floor(Math.random() * counter--);
      temp = this.deck[counter];
      this.deck[counter] = this.deck[i];
      this.deck[i] = temp;
    }
    return this.deck;
  }

  deal() {
    let hand = [];
    while (hand.length < 5) {
      hand.push(this.deck.pop());
    }
    return hand;
  }
}

let suits = ["Spades", "Hearts", "Diamonds", "Clubs"];
let values = ["Ace", "Jack", "Queen", "King", 2, 3, 4, 5, 6, 7, 8, 9, 10];
let deck = new Deck();


deck.createDeck(suits, values);
deck.shuffle();

console.log(deck.deal())

Upvotes: 0

Views: 227

Answers (2)

Jacob Thomas
Jacob Thomas

Reputation: 240

i think your issue is

fs.appendFile("OutputTask2and3.txt", msg, function(err) {
        if(err) {
          throw err;
        }
    });

is coercing msg to a string.

i would try

fs.appendFile("OutputTask2and3.txt", JSON.stringify(msg, null, '\t'), function(err) {
        if(err) {
          throw err;
        }
    });

Worth noting, you wont get the class, just a plain object being saved, but you can apply the prototype again when you need to read from the file and parse back out.

Upvotes: 0

dota2pro
dota2pro

Reputation: 7856

Use JSON.parse()

 console.log(JSON.parse(deck.deal()));

Upvotes: 1

Related Questions