0

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 ?

1 Answer 1

2

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');
    })
})
Sign up to request clarification or add additional context in comments.

2 Comments

Yes is that, thanks for the answer, anyway ill use the first solution to avoid use this out of the scope.
yes, that's what I would do too. Much cleaner to leave this as clean as possible

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.