0

Trying to get the variable random_song from the function functions.random_song

Function:

functions.random_song = () => {
  fs.readFile('auto_playlist.txt', 'utf8', function(err, data) {
    if (err) {
      console.log(`${`ERR`.red} || ${`Error fetching song from auto playlist ${err}`.red}`);
    }
    let songs = data.split('\n');
    songs.splice(-1, 1);
    var random = Math.floor(Math.random()*songs.length);
    let random_song = (songs[random]);
    return random_song;
  })
}

Attempting to callback the random song

functions.random_song(song => { 
console.log(song)
})

The code just return undefined Ideas?

Cake
  • 33
  • 5
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Evan Trimboli Aug 14 '17 at 07:08

4 Answers4

1

Your function:

functions.random_song = (callback) => {
  fs.readFile('auto_playlist.txt', 'utf8', function(err, data) {
    if (err) {
      // Do stuff
      return callback(err);
    }
    // Do stuff
    callback(null, random_song);
  })
}

And then call it:

functions.random_song((err, song) => { 
   // Do stuff
});

You may want to read more about using Promise/async-await instead of callback.

L. Meyer
  • 2,863
  • 1
  • 23
  • 26
notme
  • 424
  • 5
  • 14
0
functions.random_song = () => {
  let data = fs.readFileSync('auto_playlist.txt', 'utf8');
  let songs = data.split('\n');
  songs.splice(-1, 1);
  var random = Math.floor(Math.random()*songs.length);
  let rand_song = (songs[random]);
  return rand_song;
}

console.log(functions.random_song())

got it working, thanks for the help <3

Cake
  • 33
  • 5
  • Hey, this is `synchronous` way of reading the file, Your program will pause while reading the file. And if the file is big then the delay might be significant. Use Promise or callback approach. – Minkesh Jain Aug 14 '17 at 08:06
0

Following is the code which use Promise to handle file read and data processing task asynchronously

const fs = require('fs')
const functions = {}
functions.random_song = () => {
    return new Promise((resolve, reject) => {
        fs.readFile('auto_playlist.txt', 'utf8', function(err, data) {
            if (err) {
                console.log(err)
                reject(err)
            }
            let songs = data.split('\n');
            songs.splice(-1, 1);
            var random = Math.floor(Math.random()*songs.length);
            let random_song = (songs[random]);
            resolve(random_song);
        })
    })
}

functions.random_song()
.then(song => console.log('Song Name', song))
.catch(err => console.error('Error fetching songs', err))

console.log('It will be executed before promise is resolved')
Minkesh Jain
  • 1,140
  • 1
  • 10
  • 24
-1

fs.readFile is asynchronus and your function will return before the file is read. Use fs.readFileSync instead. Like this:

functions.random_song = () => {
  const data = fs.readFileSync('auto_playlist.txt', 'utf8');
    let songs = data.split('\n');
    songs.splice(-1, 1);
    var random = Math.floor(Math.random()*songs.length);
    let random_song = (songs[random]);
    return random_song;
}
Joakim Ericsson
  • 4,616
  • 3
  • 21
  • 29