Skip to content

Instantly share code, notes, and snippets.

@BorisOsipov
Created May 8, 2019 13:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BorisOsipov/2bcacf117da1bf3a11363608aafd1353 to your computer and use it in GitHub Desktop.
Save BorisOsipov/2bcacf117da1bf3a11363608aafd1353 to your computer and use it in GitHub Desktop.
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