-
-
Save BorisOsipov/2bcacf117da1bf3a11363608aafd1353 to your computer and use it in GitHub Desktop.
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
import axios from "axios"; | |
import * as fs from "fs"; | |
import * as path from "path"; | |
const fileExists = (filePath: fs.PathLike) => { | |
try { | |
fs.statSync(filePath); | |
} catch (err) { | |
if (err.code === "ENOENT") { return false; } | |
} | |
return true; | |
}; | |
const fileToBase64Zip = async (localPath: string) => { | |
const archiver = require("archiver"); | |
const zipData: any[] = []; | |
const source = fs.createReadStream(localPath); | |
return new Promise((resolve, reject) => { | |
const name = path.basename(localPath); | |
archiver("zip") | |
.on("error", (e: string) => { throw new Error(e); }) | |
.on("data", (data: Uint8Array) => zipData.push(data)) | |
.on("end", () => resolve(Buffer.concat(zipData).toString("base64"))) | |
.append(source, { name }) | |
.finalize((err: any) => { | |
if (err) { | |
reject(err); | |
} | |
}); | |
}); | |
}; | |
const attachFile = (locator: string, pathToFile: string) => { | |
const file = path.join(pathToFile); | |
if (!fileExists(file)) { | |
throw new Error(`File at ${file} can not be found on local system`); | |
} | |
let filePath; | |
try { | |
const fileCompressed = browser.call(() => { | |
return fileToBase64Zip(file); | |
}); | |
// @ts-ignore | |
const {config} = browser; | |
const uploadEndpoint = | |
`${config.protocol}://${config.hostname}:${config.port}${config.path}/session/${browser.sessionId}/file`; | |
const response: any = browser.call(async () => { | |
return axios.post(uploadEndpoint, { file: fileCompressed }); | |
}); | |
if (!response.data || !response.data.value) { throw new Error(`Invalid request to ${uploadEndpoint}`); } | |
filePath = response.data.value; | |
} catch (err) { | |
throw err; | |
} | |
return $(locator).addValue(filePath); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment