Search code examples
node.jsexpresspug

Node JS project returns '[object Object]' instead of displaying tweets from stream


I'm creating a Node JS project that fetches and displays tweets on a server in the form of a list. However, when I go to view the webpage after running main.js, it returns a list of '[object Object]' instead of the tweets. I have tried using JSON.stringify but to no avail. Perhaps I'm using it incorrectly?

I'm using Node.js, Express.js, and Pug.

main.js

'use strict';

const express = require('express'),
    Twitter = require('twitter'),
    passport = require('passport'),
    TwitterStrategy = require('passport-twitter').Strategy,
    request = require('request'),
    app = express(),
    tweets = [];

const T = new Twitter({
    consumer_key: 'vLHfUa437ECQDnCqbikfpHnxh',
    consumer_secret: 'ygZ6HH19vMwm3hGQnSFGKimaBNClzPZUWKoq4TKXqNnOTZPkP4',
    access_token_key: '898531406703407108-qkmMO2wAyyXjo8XIG2B59dSlWY6OXZQ',
    access_token_secret: 'vBNdwsDeaI8WNQ1gWdtp70keg0EsutgpWNeliD56uj8v6'
});

T.stream('statuses/filter', {track: 'love'}, function(stream){
    stream.on('data', function(data){
        if ('delete' in data === false){
            tweets.push(data);
        }
    });
    setTimeout(function(){
        console.log(tweets.length);
    }, 1000);
});

app.set('view engine', 'pug');
app.set('views', './views');

app.use(express.json());
app.use(express.urlencoded({
    extended: true
}));

app.use(express.static('resources'));
app.get('/', function(req, res) {
    res.setHeader("Content-Type", 'text/html');
    res.render('index', {tweets: tweets});
});

app.listen(3000, function () {
    console.log('Listening on http://localhost:3000');
});

index.pug

doctype
html
    head
        meta(charset="UTF-8")
        meta(name="viewport", content="width=device-width, initial-scale=1")
        block title
            title This is the title!
        link(rel='stylesheet', href='/css/style.css', type='text/css')
    body
        ul
            each tweet in tweets
                li= tweet

Solution

  • As Piyush pointed out, you are working with an object and need to dig further into that object before strings are pulled out.

    To display each tweet individually (which I assume you're looking to do), simply change the following:

    tweets.push(data);
    

    to this...

    tweets.push(data.text);
    

    Bam! Now you're displaying the actual text string for each tweet that matches your filter.