Skip to content

Instantly share code, notes, and snippets.

@BorisOsipov

BorisOsipov/upload.ts Secret

Created May 8, 2019
Embed
What would you like to do?
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