Reputation: 445
I have this function and is working fine:
const playlistPath = path.join(config.PLAYLIST_PATH, this.playlist.id + '.json')
let playlistString = JSON.stringify(this.playlist)
mkdirp(config.PLAYLIST_PATH, function (_) {
fs.writeFile(playlistPath, playlistString, function (err) {
if (err) return console.log('error saving album to playlist %s: %o', playlistPath, err)
console.log('The album has been added to the playlist');
})
})
But if I want to delete the var playlistString
and use the JSON.stringify
directly in is not working, the file is written with an undefined.
const playlistPath = path.join(config.PLAYLIST_PATH, this.playlist.id + '.json')
mkdirp(config.PLAYLIST_PATH, function (_) {
fs.writeFile(playlistPath, JSON.stringify(this.playlist), function (err) {
if (err) return console.log('error saving album to playlist %s: %o', playlistPath, err)
console.log('The album has been added to the playlist');
})
})
why ?
Upvotes: 0
Views: 110
Reputation: 4116
The problem is caused by the scoping of this. In the second code block when you write this.playlist
, it refers to the calling function. In this case, it's your callback function (err)...
who holds this
.
To solve the problem assign this
to a variable, then use that variable to refer to the context you want.
const playlistPath = path.join(config.PLAYLIST_PATH, this.playlist.id + '.json');
// Hold the value of "this" in a variable "ref"
const ref = this;
mkdirp(config.PLAYLIST_PATH, function (_) {
fs.writeFile(playlistPath, JSON.stringify(ref.playlist), function (err) {
if (err) return console.log('error saving album to playlist %s: %o', playlistPath, err)
console.log('The album has been added to the playlist');
})
})
Upvotes: 2