Created
June 29, 2020 06:13
-
-
Save sidouglas/32fbeefcd68541afdb74b9f1c209a877 to your computer and use it in GitHub Desktop.
Node generate a bitly shortened url link
This file contains hidden or 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
#!/usr/local/bin/node | |
const https = require("https"); | |
const TOKEN = "YOUR_BITLY_TOKEN"; | |
// get the script input variable from KBM otherwise use proces.argv.slice(2)[0] instead | |
const getStdIn = async () => { | |
let result = ''; | |
process.stdin.setEncoding('utf8'); | |
for await (const chunk of process.stdin) { | |
result += chunk; | |
} | |
return result; | |
}; | |
const shortUrl = (url) => { | |
const payload = JSON.stringify({ "long_url": url }); | |
const options = { | |
hostname: "api-ssl.bitly.com", | |
path: "/v4/bitlinks", | |
method: "POST", | |
headers: { | |
"Authorization": `Bearer ${TOKEN}`, | |
"Content-Type": "application/json", | |
"Content-Length": Buffer.byteLength(payload), | |
}, | |
}; | |
return new Promise((resolve, reject) => { | |
https.request(options, (res) => { | |
let body = ""; | |
res.on("data", (chunk) => body += chunk); | |
res.on("end", () => { | |
if (res.statusCode >= 400) { | |
reject(body); | |
} else { | |
resolve(JSON.parse(body)); | |
} | |
}); | |
}).write(payload); | |
}); | |
}; | |
(async function() { | |
try { | |
const url = await getStdIn(); // or use process argv - see function definition. | |
const result = await shortUrl(url); | |
process.stdout.write(result.link); | |
} catch (error) { | |
process.stderr.write(error); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment