Reputation: 25
This script works perfectly but I don't know how to get the name of the file. Thanks for the help
module.exports.getFile = (id, callback) =>{
fs.readFile(SECRET_PATH, (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content), id, (auth, id)=>{
var dest = fs.createWriteStream(__dirname + '/tmp.mp3'); // temporal name
const drive = google.drive({version: 'v3', auth});
drive.files.get({fileId: id, alt: 'media'},
{responseType:'stream'},
function(err, res){
res.data.on('end', () => {
console.log('done');
var filename = 'noname' ; // this is a question
fs.rename('/tmp.mp3', '/' + filename + '.mp3', function(err) {
if(err) return console.log('error: ', err);
callback(filename);
});
}).on('error', err => {
console.log('Error', err);
}).pipe(dest);
});
});
});
};
Upvotes: 1
Views: 1866
Reputation: 201553
If my understanding is correct, how about this answer?
When alt=media
is used for the method of Files: get in Drive API, the file metadata is not returned. So in order to retrieve the filename, at first, it retrieves the file metadata using the method of Files: get without alt=media
in Drive API.
var dest = fs.createWriteStream(__dirname + '/tmp.mp3'); // temporal name
const drive = google.drive({version: 'v3', auth});
drive.files.get({fileId: id, alt: 'media'},
{responseType:'stream'},
function(err, res){
res.data.on('end', () => {
console.log('done');
var filename = 'noname' ; // this is a question
fs.rename('/tmp.mp3', '/' + filename + '.mp3', function(err) {
if(err) return console.log('error: ', err);
callback(filename);
});
}).on('error', err => {
console.log('Error', err);
}).pipe(dest);
});
To:
const drive = google.drive({version: 'v3', auth});
drive.files.get({ fileId: id }, (er, re) => { // Added
if (er) {
console.log(er);
return;
}
var dest = fs.createWriteStream(__dirname + '/' + re.data.name); // Modified
drive.files.get(
{ fileId: id, alt: "media" },
{ responseType: "stream" },
function(err, res) {
res.data
.on("end", () => { // Modified
console.log("done");
})
.on("error", err => {
console.log("Error", err);
})
.pipe(dest);
}
);
});
If this was not the direction you want, I apologize.
Upvotes: 3