写文件异步node.js的,明白为什么不工作
我有这个功能,是工作的罚款:
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');
})
})
但是,如果我想删除了var playlistString
并直接在不工作使用JSON.stringify
,该文件中写入一个未定义的。
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');
})
})
为什么呢?
回答如下:问题是由this的作用域造成的。在当你写this.playlist
第二个代码块,它指的是调用函数。在这种情况下,它是谁拥有function (err)...
回调this
。
为了解决这个问题分配this
给一个变量,然后使用该变量引用到你想要的内容。
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');
})
})
写文件异步node.js的,明白为什么不工作
我有这个功能,是工作的罚款:
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');
})
})
但是,如果我想删除了var playlistString
并直接在不工作使用JSON.stringify
,该文件中写入一个未定义的。
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');
})
})
为什么呢?
回答如下:问题是由this的作用域造成的。在当你写this.playlist
第二个代码块,它指的是调用函数。在这种情况下,它是谁拥有function (err)...
回调this
。
为了解决这个问题分配this
给一个变量,然后使用该变量引用到你想要的内容。
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');
})
})