Skip to content

Instantly share code, notes, and snippets.

@ZicklePop ZicklePop/unpkg.js
Last active May 19, 2020

Embed
What would you like to do?
unpkg importer for scriptable.app, downloads modules to `iCloud Drive/Scriptable/modules`
// unpkg: like NPM but not as good
// and available in Scriptable
//
// Examples:
// - const _ = await unpkg('lodash')
// - const CryptoJS = await unpkg('crypto-js')
// - const OAuth = await unpkg('oauth-1.0a')
const unpkg = (package, file, version) => {
return new Promise((callback) => {
const jsFile = file || package
const pkgVersion = version ? `@${version}` : ''
const fm = FileManager.iCloud()
const modulesPath = fm.joinPath(fm.documentsDirectory(), 'modules/')
const modulePath = fm.joinPath(modulesPath, `${package}${pkgVersion}/`)
const filePath = fm.joinPath(modulePath, `${jsFile.split('/')[jsFile.split('/').length-1]}.js`)
if (!fm.fileExists(modulePath)) {
fm.createDirectory(modulePath, true)
}
if (!fm.fileExists(filePath) ) {
const req = new Request(`https://unpkg.com/${package}${pkgVersion}/${jsFile}.js`)
req.loadString().then(res => {
fm.writeString(filePath, `${res}`).then(() => {
callback(importModule(filePath))
})
})
} else {
fm.downloadFileFromiCloud(filePath).then(() => {
callback(importModule(filePath))
})
}
})
}
module.exports = unpkg
@kopischke

This comment has been minimized.

Copy link

kopischke commented Jan 13, 2020

Great module, that will come in very handy. You can simplify lines 16 to 21 by using Scriptable’s ability to create intermediate directories when using createDirectory, i.e. this will have the same effect:

if (!fm.fileExists(modulePath)) fm.createDirectory(modulePath, true)
@ZicklePop

This comment has been minimized.

Copy link
Owner Author

ZicklePop commented Jan 15, 2020

oh cool, thanks! i was hoping that was an option

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.