我尝试在Sails.js中将Youtube Data API与Node.js连接,但我对“fs.readFile”函数有疑问。
当我启动服务时,它返回“undefined”。
以下是我的YoutubeService代码:
module.exports = {
callYoutubeApi: function (req, res) {
// Load client secrets from a local file.
fs.readFile('api/services/client_secret.json', function processClientSecrets(err, content) {
if (err) {
sails.log('Error loading client secret file: ' + err);
return "error";
}
// Authorize a client with the loaded credentials, then call the YouTube API.
sails.log('123');
return YoutubeService.authorize(JSON.parse(content), YoutubeService.getChannel);
});
},
`/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
authorize: function (credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function (err, token) {
if (err) {
sails.log('tata');
getNewToken(oauth2Client, callback);
} else {
sails.log('tonton');
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
},
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
getNewToken: function (oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
sails.log('Authorize this app by visiting this url: ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function (code) {
rl.close();
oauth2Client.getToken(code, function (err, token) {
if (err) {
sails.log('Error while trying to retrieve access token', err);
return;
}
sails.log('getNewToken');
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
},
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
storeToken: function (token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
sails.log('Token stored to ' + TOKEN_PATH);
},
/**
* Lists the names and IDs of up to 10 files.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
getChannel: function (auth) {
var service = google.youtube('v3');
service.channels.list({
auth: auth,
part: 'snippet,contentDetails,statistics',
id: 'UCQznUf1SjfDqx65hX3zRDiA'
}, function (err, response) {
if (err) {
sails.log('The API returned an error: ' + err);
return;
}
var channels = response.items;
if (channels.length == 0) {
sails.log('No channel found.');
} else {
sails.log(channels[0]);
return channels[0];
}
});
}
}`
控制器中的呼叫:
channelData = YoutubeService.callYoutubeApi();
sails.log(channelData);
错误:
debug: undefined
debug: 123
我认为调用无效,无法读取“processClientSecrets”函数。
如果有人有意帮助我,谢谢!
答案 0 :(得分:0)
您已经创建了一个异步服务函数,但是您正在同步调用它。如果您不确定这意味着什么,请使用谷歌搜索自己“使用Node.js进行异步编程” - 这将使您的生活更轻松!
在这种情况下,您需要更改助手的函数签名:
callYoutubeApi: function (req, res) {
为:
callYoutubeApi: function (cb) {
cb
代表“回调”,它是您传入的函数,在异步代码完成时会被调用。无论您当前使用字面值调用return
,都会返回对cb
的调用。 Node中的约定是cb
的第一个参数是可能发生的任何错误,或者是null
或undefined
。第二个参数是异步代码的结果。总而言之,你得到:
callYoutubeApi: function (cb) {
// Load client secrets from a local file.
fs.readFile('api/services/client_secret.json', function processClientSecrets(err, content) {
if (err) {
// Using "return" just prevents you from accidentally continuing in this function.
return cb(err);
}
// Authorize a client with the loaded credentials, then call the YouTube API.
// This assumes that "authorize" is synchronous call that returns a value.
var auth = YoutubeService.authorize(JSON.parse(content), YoutubeService.getChannel);
return cb(undefined, auth);
});
},
您可以在控制器中调用:
YoutubeService.callYoutubeApi(function(err, channelData) {
if (err) {
return res.serverError(err);
}
// Now do something with channelData...
});