Created
June 25, 2019 21:41
-
-
Save alexander-fenster/f86ff6039e0e9dd82c268a674f1976bd to your computer and use it in GitHub Desktop.
drive-sample.js: create and update a file on Google Drive in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sample Node.js code to create and update the file on Google Drive. | |
// Pre-requisites: | |
// 1. Install Node.js | |
// 2. $ npm install express open googleapis | |
// 3. Put the JSON API key into ./key.json | |
// Usage: | |
// node drive-sample.js | |
const express = require('express'); | |
const open = require('open'); | |
const {google} = require('googleapis'); | |
const PORT = 3000; // for a local HTTP server for OAuth2 workflow | |
const key = require('./key.json'); // JSON API key file | |
// Main code here | |
async function createFile(drive, filename) { | |
const {data} = await drive.files.create({ | |
resource: { | |
name: filename | |
}, | |
media: { | |
mimeType: 'text/plain', | |
body: 'initial content' | |
}, | |
fields: 'id' | |
}); | |
return data.id; | |
} | |
async function writeCurrentTimeToFile(drive, fileId) { | |
const {data} = await drive.files.update({ | |
fileId, | |
media: { | |
mimeType: 'text/plain', | |
body: new Date().toString() | |
}, | |
}); | |
} | |
async function main() { | |
const scope = ['https://www.googleapis.com/auth/drive.file']; | |
const oauth2client = await authenticate(scope); | |
console.log('Authenticated'); | |
const drive = google.drive({ | |
version: 'v3', | |
auth: oauth2client | |
}); | |
const fileId = await createFile(drive, 'time.txt'); | |
console.log(`Created file with ID ${fileId}`); | |
await writeCurrentTimeToFile(drive, fileId); | |
console.log(`Updated the file`); | |
} | |
main().catch(console.error); | |
// OAuth2 workflow is a little bit painful | |
async function authenticate(scope) { | |
function waitForCode(url) { | |
return new Promise( (resolve, reject) => { | |
const expressApp = express(); | |
const server = expressApp.listen(PORT); | |
console.log('Server is listening, go to your browser window to continue...'); | |
expressApp.get('/oauth2callback', (req, res) => { | |
const code = req.query.code; | |
if (code === undefined) { | |
reject(new Error('Undefined code')); | |
return; | |
} | |
res.send(`OK! We've got OAuth2 code. Now please go back to your application.`); | |
console.log('Server is stopping.'); | |
server.close(); | |
resolve(code); | |
}); | |
}); | |
} | |
const oauth2client = new google.auth.OAuth2( | |
key.installed.client_id, | |
key.installed.client_secret, | |
`http://localhost:${PORT}/oauth2callback` | |
); | |
const authorizeUrl = oauth2client.generateAuthUrl({ | |
access_type: 'offline', | |
scope | |
}); | |
open(authorizeUrl); | |
const code = await waitForCode(); | |
const getTokenResponse = await oauth2client.getToken(code); | |
oauth2client.setCredentials(getTokenResponse.tokens); | |
return oauth2client; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment