How to use isDirExists method in Testcafe

Best JavaScript code snippet using testcafe

createJsFile.js

Source:createJsFile.js Github

copy

Full Screen

1// app/v2/controller/createJsFile.js2// 这不是一个RESTful接口,并不操作“资源”,而是用于生成需要的文件,是一个“动作”3// 本页用到了大量的js中fs api,建议参考 http://nodejs.cn/api/fs.html 页面4// 由于 fs api用到了大量的callback函数,造成程序结构会非常难看(callback hell)5// 因此根据需要,尝试在代码不会被经常调用的场景,选择sync(同步)来避免callback(方法1)6// 同时也提供了第二种思路: 把callback包装成Promise接口(方法2)7// 简单的说就是利用util.promisify来封装fs的所有函数(注意require)8// 变成 promise 之后就可以愉快的配合 try/catch 结构使用 async/await 了9// 本页采用了的是方法2,毕竟异步操作不会造成阻塞10// 再提供一种实验性的思路,fsPromise API也已经在node10中提供实验性的使用了11// 也就是不需要转化的方法二,值得关注跟进12'use strict';13const Controller = require('egg').Controller;14const { promisify } = require('util');15const { URL } = require('url');16const fs = require('fs');17// 文件库的根目录位置18const reservePath = 'file:///var/www/oj_reserve/';19class CreateJsFileController extends Controller {20 async create() {21 const ctx = this.ctx;22 const params = ctx.request.body.data;23 if (params.type === undefined) {24 ctx.throw(406, '必须指定需生成的文件类型');25 }26 switch (params.type) {27 case 'testcases': // 从设计上来讲 testcases 只有在前端增添测试用例时才会被用到,较少使用28 await this.createTestcaseFile(params.id);29 break;30 case 'judge': // 用于生成判题文件31 await this.createJudgeFile(params);32 break;33 default: ctx.throw(406, '无效的文件类型');34 }35 }36 async createTestcaseFile(id) {37 const ctx = this.ctx;38 // 注意,这里规定了只有测试用例表中是 status 是 done 的情况才会生成用例及判题文档。39 const row = {40 id,41 status: 'done',42 };43 const result = await ctx.service.v2.testcases.show(row);44 // console.log(result);45 if (result.id === undefined) {46 ctx.throw(400, 'id为' + row.id + '的测试用例正在编辑中或不存在,无法生成测试用例文档。');47 }48 if (result.programLang !== 'js') {49 ctx.throw(406, '这不是一份JavaScript语言的测试用例');50 }51 // 在以 codingQeustions 的 id为名的文件夹中创建符合Js语法可被Js直接调用的测试用例文档 testcase.js52 const dataFileUrl = new URL(reservePath + result.cqId + '/testcases.js');53 // const runFileUrl = new URL(reservePath + testcase.cqId + '/run.js');54 const dirUrl = new URL(reservePath + result.cqId);55 // 检查对应文件夹是否存在,如果不存在则生成文件夹(Sync同步版本)56 // if (!fs.existsSync(dirUrl)) {57 // await this.createDir(dirUrl);58 // }59 // 检测文件夹是否存在的异步版本60 let isDirExists = false;61 const accessPromise = promisify(fs.access, fs);62 // 找不到文件夹会报错,被catch捕获63 await accessPromise(dirUrl, fs.constants.F_OK).then(function() {64 isDirExists = true;65 }).catch(function() {66 isDirExists = false;67 });68 if (!isDirExists) {69 await this.createDir(dirUrl);70 }71 // 处理 JSON 字符串72 const inputArray = JSON.parse(result.inputData);73 const outputArray = JSON.parse(result.outputData);74 // 利用JSON 值-值 配对的特性,将两个数组按项合并75 const testcaseMap = new Map(76 inputArray.map((item, i) => [ item, outputArray[i] ])77 );78 // console.log(testcaseMap);79 // 再将Map转化为每项为 [ 值1, 值2] 这样的二维数组,80 // 像我这个例子中 值1是本身就是个数组,所以是个三维数组81 // 并用JSON字符串的形式保存82 const testcaseContent = JSON.stringify([ ...testcaseMap ]);83 // console.log(testcaseContent);84 const content = 'const testCases = ' + testcaseContent + '\nmodule.exports = testCases';85 const writeFilePromise = promisify(fs.writeFile, fs);86 await writeFilePromise(dataFileUrl, content).then(function() {87 ctx.status = 201;88 }).catch(function(err) {89 ctx.throw(400, err);90 });91 }92 async createJudgeFile(params) {93 const ctx = this.ctx;94 // console.log(param);95 if (params.cqId === undefined || params.uId === undefined) {96 ctx.throw(406, '必须提供答题人id和编程题id');97 }98 // 安全冗余,检查是否存在这个用户,防止绕过验证作弊的可能99 // 优化运行效率时可取消此检查100 const user = await ctx.service.v2.authentications.show({ id: params.uId });101 if (user === null) {102 ctx.throw(406, '非法的用户id');103 }104 // 需要 codingQuestions 中的 tpId 和 preFuncName105 const quest = await ctx.service.v2.codingQuestions.show({ id: params.cqId });106 if (quest === null) {107 ctx.throw(406, '该编程题不存在');108 }109 if (quest.programLang !== 'js') {110 ctx.throw(406, '这是一道要求用' + quest.programLang + '语言描述的编程题,无法用JavaScript语言来判题');111 }112 if (quest.tpId === null) {113 ctx.throw(406, '与此题相关的判题程序未设定,无法判题,请联系相关教师');114 }115 // 需要 testProgram 中的 testCode, 用于之后的判题文件生成116 const testProgram = await ctx.service.v2.testPrograms.show({ id: quest.tpId, status: 'done' });117 if (testProgram === null) {118 ctx.throw(406, '与此题相关的判题程序未设定或正在编辑中,无法判题,请联系相关教师');119 }120 // 需要 codingRecord 中的 code 拿来判题121 const codingRecord = await ctx.service.v2.codingRecords.show({ uId: params.uId, cqId: params.cqId, status: 'unsolved' });122 if (codingRecord === null) {123 ctx.throw(406, '未在数据库中找到用户提交的代码,无法判题');124 }125 if (quest.timeLimit === 0) {126 // 若codingQuestiosn中的timeLimit为0(不限制),则给5分钟的运行时间(几乎等于不限制)127 quest.timeLimit = 300000;128 }129 let hiddenCodeLine = '';130 if (quest.hiddenCode !== null) {131 hiddenCodeLine = quest.hiddenCode + '\n';132 }133 // 拼接出完整的,可以带入testcases并运行的判题文档134 let content = hiddenCodeLine +135 codingRecord.code + '\n' +136 'let timeLimit = ' + quest.timeLimit + '\n' +137 'let solution = ' + quest.preFuncName + '\n' +138 'const testCases = require("../' + params.cqId + '/testcases.js")\n' +139 testProgram.testCode;140 // 替换文档中所有的windows换行(CRLF \r\n)成linux换行(\n)141 content = content.replace(/\r\n/g, '\n');142 // 指定生成文档的名称: oj_reserve/submitCode 目录下,题目Id-用户Id,143 // 例如1号用户做5号题的 javascript(js)题目,则文档名为 oj_reserver/submitCode/5-1.js144 const judgeFileUrl = new URL(reservePath + 'submitCode/' + params.cqId + '-' + params.uId + '.' + testProgram.programLang);145 // 将写文件接口包装成promise接口146 const writeFilePromise = promisify(fs.writeFile, fs);147 await writeFilePromise(judgeFileUrl, content).then(function() {148 ctx.status = 201;149 }).catch(function(err) {150 ctx.throw(400, err);151 });152 }153 // 建立文件夹,使用了前文提到的方法2154 async createDir(dirUrl) {155 const ctx = this.ctx;156 const mkdirPromise = promisify(fs.mkdir, fs);157 try {158 await mkdirPromise(dirUrl); // , function(error) {159 } catch (error) {160 // 啰嗦一句,根据middleware中的相关定义161 // 在生成环境里5xx错误的具体信息是不会传递到前端的(开发环境会)162 // 因此在这里输出服务器敏感性息163 ctx.throw(500, dirUrl + '文件夹生成失败,请检查服务器权限设置');164 }165 // 修改文件所有权(交给特定用户)166 const chownPromise = promisify(fs.chown, fs);167 try {168 await chownPromise(dirUrl, 1000, 1000);169 } catch (error) {170 ctx.throw(500, dirUrl + '文件夹修改权限失败,请检查服务器权限设置');171 }172 }173}...

Full Screen

Full Screen

fsUtils.js

Source:fsUtils.js Github

copy

Full Screen

...7const handleErr = (err) => console.error(err.message);8const files = {};9files.removeDistDir = () => {10 return new Promise((resolve) => {11 isDirExists(paths.distDir())12 .then((isDirExists) => {13 if (isDirExists) {14 files15 .removeDirectory(paths.distDir())16 .then(() => {17 resolve(true);18 })19 .catch(handleErr);20 } else {21 console.log("The folder doesn't exists", paths.distDir());22 resolve(false);23 }24 })25 .catch(handleErr);26 });27};28files.copyDirs = (directories, dirsPathSrc, dirsPathDest) => {29 return new Promise((resolve, rejecte) => {30 const errors = [];31 let count = 0;32 let dirPathSrc = '';33 let dirPathDest = '';34 const opCompleted = () => {35 if (errors.length < 1) {36 resolve();37 } else {38 errors.forEach(handleErr);39 rejecte(40 `Failed: Copying folder, with ${41 errors.length42 }, errors\n ${paths.distDir()}`43 );44 }45 };46 directories.forEach((dirName) => {47 const re = /[\\|/]+app$/gi;48 dirPathSrc = path.join(dirsPathSrc, dirName);49 dirPathDest = path.join(dirsPathDest, dirName);50 dirPathDest = dirPathDest.replace(re, '');51 files52 .copyDir(dirPathSrc, dirPathDest)53 .then()54 .catch((err) => errors.push(err.message))55 .finally(() => {56 count++;57 if (count >= directories.length) opCompleted();58 });59 });60 });61};62files.copyDir = (srcDirPath, destDirPath) => {63 return new Promise((resolve, rejecte) => {64 let count = 0;65 const errors = [];66 const opCompleted = () => {67 if (errors.length < 1) {68 console.log('Folder copied\t', destDirPath);69 resolve();70 } else {71 errors.forEach(handleErr);72 rejecte(73 `Failed: Copying folder, with${74 errors.length75 } errors\n${paths.distDir()}`76 );77 }78 };79 createDirectory(destDirPath)80 .then(() =>81 getFilesList(srcDirPath)82 .then((itemsPath) => {83 if (itemsPath.length > 0) {84 itemsPath.forEach((itemPath) =>85 isDirOrFile(itemPath)86 .then((isFileDir) => {87 if (isFileDir === FILE) {88 files89 .copyFile(itemPath, destDirPath)90 .then()91 .catch(handleErr)92 .finally(() => {93 count++;94 if (count === itemsPath.length) opCompleted();95 });96 } else if (isFileDir === DIR) {97 const destDirName = path.basename(itemPath);98 const newDestDirPath = path.join(99 destDirPath,100 destDirName101 );102 files103 .copyDir(itemPath, newDestDirPath)104 .then()105 .catch(handleErr)106 .finally(() => {107 count++;108 if (count === itemsPath.length) opCompleted();109 });110 } else {111 count++;112 }113 })114 .catch(handleErr)115 );116 } else {117 resolve();118 }119 })120 .catch(handleErr)121 )122 .catch(handleErr);123 });124};125files.copyFiles = (listFiles, destDirPath) => {126 return new Promise((resolve, rejecte) => {127 const errors = [];128 let count = 0;129 const opCompleted = () => {130 if (errors.length < 1) {131 console.log(`Files copied ${listFiles.length} files\n`, listFiles);132 resolve();133 } else {134 console.error(135 'Failed: Copying files, with ',136 errors.length,137 ' errors\n',138 errors139 );140 rejecte();141 }142 };143 if (Array.isArray(listFiles) && listFiles.length > 0) {144 listFiles.forEach((item) => {145 isDirOrFile(item)146 .then((isFileDir) => {147 if (isFileDir === FILE) {148 files149 .copyFile(item, destDirPath)150 .then()151 .catch((err) => errors.push(err))152 .finally(() => {153 count++;154 if (count >= listFiles.length) opCompleted();155 });156 } else if (isFileDir === DIR) {157 files158 .copyDir(item, destDirPath)159 .then()160 .catch((err) => errors.push(err))161 .finally(() => {162 count++;163 if (count >= listFiles.length) opCompleted();164 });165 } else {166 count++;167 console.error(168 'Error: Could not copy, must be (file | folder)\n',169 item170 );171 }172 })173 .catch(handleErr);174 });175 } else if (listFiles.length < 1) {176 resolve();177 } else {178 rejecte(`Error: It is not an Array of list files\n${listFiles}`);179 }180 });181};182files.copyFile = (srcFilePath, destDirPath) => {183 return new Promise((resolve, rejecte) => {184 const dirName = path.dirname(srcFilePath);185 const baseName = path.basename(srcFilePath);186 const destFilePath = path.join(destDirPath, baseName);187 const copyIt = () => {188 fsPromises189 .copyFile(srcFilePath, destFilePath)190 .then(() => {191 console.log('File copied\t', destFilePath);192 resolve();193 })194 .catch(handleErr);195 };196 isDirOrFile(dirName)197 .then((isFileDir) => {198 if (isFileDir === DIR) {199 isFileDirExists(destDirPath)200 .then((isFileDir) => {201 if (isFileDir === DIR) {202 copyIt();203 } else {204 createDirectory(destDirPath).then(copyIt()).catch(handleErr);205 }206 })207 .catch(handleErr);208 } else {209 // createDirectory(dirName)210 // .then(copyIt())211 // .catch(handleErr);212 rejecte({213 message: `214 Error: unable to copythe file: ${destFilePath}215 The directory ${srcFilePath} dosn't exists`,216 });217 }218 })219 .catch(handleErr);220 });221};222files.removeFile = (srcFilePath) => {223 return new Promise((resolve) =>224 fsPromises225 .unlink(srcFilePath)226 .then(() => {227 console.log('File removed\t', srcFilePath);228 resolve();229 })230 .catch(handleErr)231 );232};233files.removeDirectory = (dirPath) => {234 return new Promise((resolve) => {235 let count = 0;236 const opCompleted = () =>237 fsPromises238 .rmdir(dirPath)239 .then(() => {240 console.log('Folder removed\t', dirPath);241 resolve(dirPath);242 })243 .catch(handleErr);244 isDirExists(dirPath)245 .then((isDirExists) => {246 if (isDirExists) {247 getFilesList(dirPath)248 .then((itemsPath) => {249 if (itemsPath.length < 1) {250 opCompleted();251 } else {252 itemsPath.forEach((itemPath) =>253 isDirOrFile(itemPath)254 .then((isFileDir) => {255 if (isFileDir === FILE) {256 files257 .removeFile(itemPath)258 .then(() => count++)259 .catch(handleErr)260 .finally(() => {261 if (count >= itemsPath.length) opCompleted();262 });263 } else if (isFileDir === DIR) {264 files265 .removeDirectory(itemPath)266 .then(() => count++)267 .catch(handleErr)268 .finally(() => {269 if (count >= itemsPath.length) opCompleted();270 });271 }272 })273 .catch(handleErr)274 );275 }276 })277 .catch(handleErr);278 } else {279 resolve(false);280 }281 })282 .catch(handleErr);283 });284};285const isDirOrFile = (ItemPath) => {286 return new Promise((resolve, rejecte) => {287 fsPromises288 .stat(ItemPath)289 .then((item) => {290 if (item.isDirectory()) {291 resolve(DIR);292 } else if (item.isFile()) {293 resolve(FILE);294 } else {295 rejecte("It's not a file or a folder", ItemPath);296 }297 })298 .catch(handleErr);299 });300};301const isDirExists = (dirPath) => {302 return new Promise((resolve) => {303 fsPromises304 .stat(dirPath)305 .then(() => {306 isDirOrFile(dirPath)307 .then((isFileDir) => {308 const isDir = isFileDir === DIR ? true : false;309 resolve(isDir);310 })311 .catch(handleErr);312 })313 .catch((err) => {314 if (err.code === 'ENOENT') resolve(false);315 });316 });317};318const isFileDirExists = (dirPath) => {319 return new Promise((resolve) => {320 fsPromises321 .stat(dirPath)322 .then(() => resolve(true))323 .catch((err) => {324 if (err.code === 'ENOENT') resolve(false);325 });326 });327};328const createDirectory = (dirPath) => {329 return new Promise((resolve) => {330 isDirExists(dirPath)331 .then((isDirExists) => {332 if (!isDirExists) {333 fsPromises334 .mkdir(dirPath, { recursive: true })335 .then(() => {336 console.log('Folder created\t', dirPath);337 resolve();338 })339 .catch(handleErr);340 } else {341 resolve();342 }343 })344 .catch(handleErr);...

Full Screen

Full Screen

filesystem.js

Source:filesystem.js Github

copy

Full Screen

1const path = require('path').posix2const {S3Client, ListObjectsV2Command, HeadObjectCommand, GetObjectCommand, PutObjectCommand, DeleteObjectCommand, CopyObjectCommand} = require('@aws-sdk/client-s3');3const {CognitoIdentityClient} = require("@aws-sdk/client-cognito-identity");4const {fromCognitoIdentityPool} = require("@aws-sdk/credential-provider-cognito-identity");5const cognitoIdentityClient = new CognitoIdentityClient({6 region: 'ap-northeast-2'7});8const s3 = new S3Client({9 region: 'ap-northeast-2',10 credentials: fromCognitoIdentityPool({11 client: cognitoIdentityClient,12 identityPoolId: 'ap-northeast-2:6fafadd5-4e84-4213-83a4-8b8e5bf7aef2'13 }),14});15const s3BucketName = 'taeguk-github-io-public'16// NOTE: There is no trailing slash in return value.17function getAbsoluteCurrentPath () {18 return $('.current_location').first().text().trim()19}20function setAbsolueCurrentPath (absCurPath) {21 // remove trailing slash except foremost slash22 absCurPath = absCurPath.trim()23 absCurPath = absCurPath === '/' ? '/' : absCurPath.replace(/\/$/, "")24 $('.current_location').text(absCurPath)25}26function getAbsolutePath (path_) {27 const absCurPath = getAbsoluteCurrentPath()28 let absPath29 if (path_.startsWith('/'))30 absPath = path_31 else32 absPath = absCurPath + '/' + path_33 absPath = path.normalize(absPath)34 return absPath35}36exports.cd = async (dirPath) => {37 let absDirPath = getAbsolutePath(dirPath)38 const isDirExists = await checkDirExists(absDirPath)39 if (isDirExists)40 setAbsolueCurrentPath(absDirPath)41 else {42 const isFileExists = await checkFileExists(absDirPath)43 if (isFileExists)44 throw new Error('not a directory: ' + dirPath)45 else46 throw new Error('no such file or directory: ' + dirPath)47 }48}49exports.autoCompleteDir = async (keyword) => {50 const absCurPath = getAbsoluteCurrentPath()51 // First, try to find matched directory in childs.52 let prefix = getDirKeyForS3(absCurPath + '/' + keyword)53 let data = await listObjectsFromS3(prefix)54 // If not found, try to matched directory in siblings.55 if (data.CommonPrefixes.length === 0) {56 // Remove trailing slash.57 prefix = prefix.replace(/\/$/, "")58 data = await listObjectsFromS3(prefix)59 }60 if (data.CommonPrefixes.length > 0)61 return path.relative(absCurPath, data.CommonPrefixes[0].Prefix) + '/'62 else63 return keyword64}65exports.autoCompleteFile = async (keyword) => {66 const absCurPath = getAbsoluteCurrentPath()67 const prefix = getFileKeyForS3(absCurPath + '/' + keyword)68 const data = await listObjectsFromS3(prefix)69 if (data.Contents.length > 0)70 return path.relative(absCurPath, data.Contents[0].Key)71 else if (data.CommonPrefixes.length > 0)72 return path.relative(absCurPath, data.CommonPrefixes[0].Prefix) + '/'73 else74 return keyword75}76async function checkDirExists (absPath) {77 const { isDirExists, _ } = await checkDirExistsAndEmpty(absPath)78 return isDirExists79}80async function checkDirExistsAndEmpty (absPath) {81 const dirData = await listObjectsOfDirFromS3(absPath, excludeDirFromContents = false)82 const isDirExists = dirData.CommonPrefixes.length > 0 || dirData.Contents.length > 083 const isDirExistsAndEmpty = dirData.CommonPrefixes.length === 0 && dirData.Contents.length === 184 return { isDirExists, isDirExistsAndEmpty }85}86async function checkFileExists (absPath) {87 if (absPath.substr(-1) === '/')88 return false89 const fileKey = getFileKeyForS3(absPath)90 let isFileExists91 try {92 await s3.send(new HeadObjectCommand({Bucket: s3BucketName, Delimiter: '/', Key: fileKey}))93 isFileExists = true94 } catch (err) {95 if (err.message === 'NotFound')96 isFileExists = false97 else98 throw err99 }100 return isFileExists101}102function getFileKeyForS3 (absPath) {103 // - make it sure to be normalized.104 // - remove foremost slash.105 let key = path.normalize(absPath)106 key = key[0] === '/' ? key.substring(1) : key107 return key108}109function getDirKeyForS3 (absDirPath) {110 // make it sure to be normalized like "/aaaaa/bb/ccc".111 let key = path.normalize(absDirPath)112 // "/" -> ""113 // "/aaaaa/bb/ccc" -> "aaaaa/bb/ccc/"114 // "/aaaaa/bb/ccc/" -> "aaaaa/bb/ccc/"115 return key === '/' ? '' : key.substring(1).replace(/\/$/, "") + '/'116}117async function listObjectsOfDirFromS3 (absDirPath, excludeDirFromContents = true) {118 const key = getDirKeyForS3(absDirPath)119 return await listObjectsFromS3(key, excludeDirFromContents)120}121async function listObjectsFromS3 (prefix, excludeDirFromContents = true) {122 let data = await s3.send(new ListObjectsV2Command({Bucket: s3BucketName, Delimiter: '/', Prefix: prefix}))123 if (data.CommonPrefixes === undefined)124 data.CommonPrefixes = []125 if (data.Contents === undefined)126 data.Contents = []127 // There can be object which key is same to directory exactly.128 // We should erase it to make reasonable output to users.129 if (excludeDirFromContents && prefix.substr(-1) === '/') {130 data.Contents = data.Contents.filter((content) => {131 return content.Key !== prefix132 })133 }134 return data135}136exports.ls = async (dirPath = '') => {137 const absDirPath = getAbsolutePath(dirPath)138 const isDirExists = await checkDirExists(absDirPath)139 if (!isDirExists) {140 const isFileExists = await checkFileExists(absDirPath)141 if (isFileExists)142 throw new Error('not a directory: ' + dirPath)143 else144 throw new Error('no such file or directory: ' + dirPath)145 }146 const data = await listObjectsOfDirFromS3(absDirPath)147 let names = []148 for (const commonPrefix of data.CommonPrefixes) {149 const dirPath = commonPrefix.Prefix150 const dirName = path.basename(dirPath) + '/'151 names.push(dirName)152 }153 for (const content of data.Contents) {154 const filePath = content.Key155 const fileName = path.basename(filePath)156 const fileSize = content.Size157 const lastModified = content.LastModified158 names.push(fileName)159 }160 names.sort()161 let result = $('<pre>')162 for (const name of names) {163 result.append($(document.createTextNode(name + '\n')))164 }165 return result166}167exports.mkdir = async (dirPath) => {168 const absDirPath = getAbsolutePath(dirPath)169 const isDirExists = await checkDirExists(absDirPath)170 if (isDirExists)171 throw new Error('directory already exists: ' + dirPath)172 else {173 const isFileExists = await checkFileExists(absDirPath)174 if (isFileExists)175 throw new Error('file exists: ' + dirPath)176 else {177 const key = getDirKeyForS3(absDirPath)178 await s3.send(new PutObjectCommand({Bucket: s3BucketName, Key: key}))179 }180 }181}182exports.rmdir = async (dirPath) => {183 const absDirPath = getAbsolutePath(dirPath)184 const { isDirExists, isDirExistsAndEmpty } = await checkDirExistsAndEmpty(absDirPath)185 if (isDirExists) {186 if (isDirExistsAndEmpty) {187 const key = getDirKeyForS3(absDirPath)188 await s3.send(new DeleteObjectCommand({Bucket: s3BucketName, Key: key}))189 }190 else191 throw new Error('directory not empty: ' + dirPath)192 }193 else {194 const isFileExists = await checkFileExists(absDirPath)195 if (isFileExists)196 throw new Error('not a directory: ' + dirPath)197 else198 throw new Error('no such file or directory: ' + dirPath)199 }200}201exports.cat = async (filePath) => {202 const absFilePath = getAbsolutePath(filePath)203 try {204 const key = getFileKeyForS3(absFilePath)205 const {Body} = await s3.send(new GetObjectCommand({Bucket: s3BucketName, Key: key}))206 const data = await Body.getReader().read()207 const text = data.value === undefined ? '' : Buffer.from(data.value).toString('utf-8')208 return $('<pre>').text(text)209 } catch (err) {210 if (err.message === 'NoSuchKey')211 throw new Error('no such file: ' + filePath)212 else213 throw err214 }215}216async function assertFileExists (filePath) {217 const absFilePath = getAbsolutePath(filePath)218 const isFileExists = await checkFileExists(absFilePath)219 if (!isFileExists) {220 const isDirExists = await checkDirExists(absFilePath)221 if (isDirExists)222 throw new Error('is a directory: ' + filePath)223 else224 throw new Error('no such file or directory: ' + filePath)225 }226}227async function assertFileIsCreatable (filePath) {228 const absFilePath = getAbsolutePath(filePath)229 const lastChar = absFilePath.substr(-1)230 const isDirExists = await checkDirExists(absFilePath)231 if (isDirExists)232 throw new Error('is a directory: ' + filePath)233 // The path means a directory. So, it can't be a file.234 // Use same error message in general shell.235 if (lastChar === '/')236 throw new Error('no such file or directory: ' + filePath)237}238exports.redirectToFile = async (filePath, content) => {239 await assertFileIsCreatable(filePath)240 const absFilePath = getAbsolutePath(filePath)241 const key = getFileKeyForS3(absFilePath)242 await s3.send(new PutObjectCommand({Bucket: s3BucketName, Key: key, Body: content}))243}244exports.rm = async (filePath) => {245 await assertFileExists(filePath)246 const absFilePath = getAbsolutePath(filePath)247 const key = getFileKeyForS3(absFilePath)248 await s3.send(new DeleteObjectCommand({Bucket: s3BucketName, Key: key}))249}250exports.cp = async (srcFilePath, dstFilePath) => {251 await assertFileExists(srcFilePath)252 await assertFileIsCreatable(dstFilePath)253 const absSrcFilePath = getAbsolutePath(srcFilePath)254 const absDstFilePath = getAbsolutePath(dstFilePath)255 try {256 const srcKey = getFileKeyForS3(absSrcFilePath)257 // NOTE: It is inserted to http header as X-Amz-Copy-Source. But aws sdk don't encode the value.258 // So we should encodeURI for the value ourself.259 const copySource = encodeURIComponent('/' + s3BucketName + '/' + srcKey)260 const dstKey = getFileKeyForS3(absDstFilePath)261 await s3.send(new CopyObjectCommand({Bucket: s3BucketName, CopySource: copySource, Key: dstKey}))262 return263 } catch (err) {264 if (err.message === 'NoSuchKey')265 throw new Error('no such file: ' + filePath)266 else267 throw err268 }...

Full Screen

Full Screen

meteor.mobile.server.js

Source:meteor.mobile.server.js Github

copy

Full Screen

1class _Mobile {2 constructor() {3 this.version = '1.0.0';4 this.shell = Npm.require( 'shelljs/global' );5 this.colors = Npm.require( 'colors' );6 this.figures = Npm.require( 'figures' );7 this.fs = Npm.require( 'fs' );8 this.appDir = pwd().replace(/\/\.meteor.*$/, '');9 this.appDirs = ls('-A', this.appDir);10 }11 get( module ) {12 return Npm.require( module );13 }14 prepareClientDir() {15 let isDirExists = _.contains(this.appDirs, 'client');16 if (! isDirExists ) {17 echo(this.figures.error, '[Mobile] Could not find directory: "client" in your project root, creating...' );18 mkdir(this.appDir + '/client');19 }20 }21 preparePackagesDir() {22 let isDirExists = _.contains(this.appDirs, 'packages');23 if (! isDirExists ) {24 echo(this.figures.error, '[Mobile] Could not find directory: "packages" in your project root, creating...' );25 mkdir(this.appDir + '/packages');26 }27 }28 mobileSettingsFile() {29 return {30 "Fast click": true,31 "Launch screen": true,32 "Mobile statusbar": true,33 "Iron Router": false,34 "Flow Router": false,35 "Semantic UI": false,36 "Ionic Framework UI": false,37 "Faker": false,38 "Geolocation": false,39 "Camera": false,40 "Reactive dict": false,41 "Reactive var": false,42 "create meteor's Mobile Config File": false,43 "Moment": false44 };45 }46 isSettingsFileExists() {47 let isDirExists = _.contains(this.appDirs, '.mobile.json');48 if (! isDirExists ) {49 echo(this.figures.error, '[Mobile] Could not find file: ".mobile.json" in your project root, creating...' );50 echo( JSON.stringify(this.mobileSettingsFile(), null, 2) ).to( this.appDir + '/.mobile.json' );51 }52 return true;53 }54 translateFriendlyNames( friendlyName ) {55 let dict = {56 "Fast click": "fastclick",57 "Launch screen": 'launch-screen',58 "Mobile statusbar": 'mobile-status-bar',59 "Iron Router": 'iron:router',60 "Flow Router": 'kadira:flow-router',61 "Semantic UI": 'semantic:ui',62 "Ionic Framework UI": 'driftyco:ionic',63 "Faker": 'digilord:faker',64 "Geolocation": 'mdg:geolocation',65 "Camera": 'mdg:camera',66 "Reactive dict": 'reactive-dict',67 "Reactive var": 'reactive-var',68 "create meteor's Mobile Config File": 'mobile-config',69 "Moment": 'momentjs:moment'70 };71 return dict[friendlyName];72 }73 createMobileConfig() {74 console.log('creating mobile-config');75 let sample = `76 // This section sets up some basic app metadata,77 // the entire section is optional.78 App.info({79 id: 'com.example.matt.uber',80 name: 'über',81 description: 'Get über power in one button click',82 author: 'Matt Development Group',83 email: 'contact@example.com',84 website: 'http://example.com'85 });86 // Set up resources such as icons and launch screens.87 App.icons({88 'iphone': 'icons/icon-60.png',89 'iphone_2x': 'icons/icon-60@2x.png',90 // ... more screen sizes and platforms ...91 });92 App.launchScreens({93 'iphone': 'splash/Default~iphone.png',94 'iphone_2x': 'splash/Default@2x~iphone.png',95 // ... more screen sizes and platforms ...96 });97 // Set PhoneGap/Cordova preferences98 App.setPreference('BackgroundColor', '0xff0000ff');99 App.setPreference('HideKeyboardFormAccessoryBar', true);100 App.setPreference('Orientation', 'default');101 App.setPreference('Orientation', 'all', 'ios');102 // Pass preferences for a particular PhoneGap/Cordova plugin103 App.configurePlugin('com.phonegap.plugins.facebookconnect', {104 APP_ID: '1234567890',105 API_KEY: 'supersecretapikey'106 });107 `;108 if ( cat(this.appDir + '/mobile-config.js') === '' ) {109 echo( sample ).to( this.appDir + '/mobile-config.js' );110 }111 return true;112 }113 check( packages ) {114 this.packages = packages;115 return this;116 }117 using( settingsFile ) {118 let packages = this.packages;119 let settings = JSON.parse(settingsFile);120 for (let packageName in settings) {121 if (settings.hasOwnProperty(packageName)) {122 if ( this.translateFriendlyNames(packageName) === 'mobile-config' ) {123 this.createMobileConfig();124 } else {125 console.log(`[Meteor Mobile]: ${settings[packageName] ? 'installing' : 'removing'}... `, this.translateFriendlyNames(packageName));126 var package = exec(`meteor ${settings[packageName] ? 'add' : 'remove'} ${this.translateFriendlyNames(packageName)}`, { silent: true }).output;127 console.log(package);128 }129 }130 }131 }132 watchSettings( cb ) {133 this.fs.watchFile(this.appDir + '/.mobile.json', function (current, prev) {134 console.log('[Meteor Mobile]: Config changed, updating...');135 cb();136 });137 }138 init() {139 if (! this.isSettingsFileExists() ) {140 console.log(this.figures.star + this.figures.star + this.figures.star + ' ===[[[ Welcome to Meteor Mobile ]]]=== '.green + this.figures.star + this.figures.star + this.figures.star);141 this.prepareClientDir();142 } else {143 // let appPackages = cat( this.appDir + '/.meteor/packages' );144 let appPackages = exec('meteor list', { silent: true }).output;145 let settingsFile = cat( this.appDir + '/.mobile.json' );146 this.watchSettings(() => {147 Mobile.check(appPackages).using(settingsFile)148 });149 }150 }151}152Mobile = new _Mobile();...

Full Screen

Full Screen

assertion-helper.js

Source:assertion-helper.js Github

copy

Full Screen

...40function checkTestDir (testDirPath, forError, expectedSubDirCount, expectedScreenshotCount) {41 var subDirs = fs42 .readdirSync(testDirPath)43 .filter(function (file) {44 return isDirExists(path.join(testDirPath, file));45 });46 if (subDirs.length !== expectedSubDirCount)47 return false;48 var dirPath = null;49 return subDirs.every(function (dir) {50 dirPath = forError ? path.join(testDirPath, dir, ERRORS_DIR_NAME) : path.join(testDirPath, dir);51 return getScreenshotFilesCount(dirPath) === expectedScreenshotCount;52 });53}54exports.errorInEachBrowserContains = function errorInEachBrowserContains (testErrors, message, errorIndex) {55 if (testErrors instanceof Error)56 throw testErrors;57 // NOTE: if errors are the same in different browsers58 if (Array.isArray(testErrors))59 expect(testErrors[errorIndex]).contains(message);60 //NOTE: if they are different61 else {62 Object.keys(testErrors).forEach(function (key) {63 expect(testErrors[key][errorIndex]).contains(message);64 });65 }66};67exports.errorInEachBrowserContainsRegExp = function errorInEachBrowserContains (testErrors, messageRE, errorIndex) {68 if (testErrors instanceof Error)69 throw testErrors;70 // NOTE: if errors are the same in different browsers71 if (Array.isArray(testErrors))72 expect(messageRE.test(testErrors[errorIndex])).equals(true);73 //NOTE: if they are different74 else {75 Object.keys(testErrors).forEach(function (key) {76 expect(messageRE.test(testErrors[key][errorIndex])).equals(true);77 });78 }79};80exports.errorInEachBrowserNotContains = function errorInEachBrowserNotContains (testErrors, message, errorIndex) {81 if (testErrors instanceof Error)82 throw testErrors;83 // NOTE: if errors are the same in different browsers84 if (Array.isArray(testErrors))85 expect(testErrors[errorIndex]).not.contains(message);86 //NOTE: if the are different87 else {88 Object.keys(testErrors).forEach(function (key) {89 expect(testErrors[key][errorIndex]).not.contains(message);90 });91 }92};93exports.isScreenshotDirExists = function () {94 return isDirExists(SCREENSHOTS_PATH);95};96exports.checkScreenshotsCreated = function checkScreenshotsCreated (forError, count, customPath, runDirCount) {97 var expectedSubDirCount = config.browsers.length;98 var expectedScreenshotCount = count || 2;99 if (!isDirExists(SCREENSHOTS_PATH))100 return false;101 var taskDirs = fs.readdirSync(SCREENSHOTS_PATH);102 if (!taskDirs || !taskDirs[0] || taskDirs.length !== 1)103 return false;104 var taskDirPath = path.join(SCREENSHOTS_PATH, taskDirs[0]);105 if (customPath) {106 var customDirExists = taskDirPath.indexOf(customPath) !== -1;107 var hasScreenshots = getScreenshotFilesCount(taskDirPath, customPath) ===108 expectedScreenshotCount * expectedSubDirCount;109 return customDirExists && hasScreenshots;110 }111 if (!TASK_DIR_RE.test(taskDirs[0]))112 return false;113 var testDirs = fs.readdirSync(taskDirPath);114 if (!testDirs || !testDirs.length || testDirs.length !== 1)115 return false;116 var basePath = null;117 var dirs = null;118 var dirNameRE = null;119 var dirPath = null;120 if (runDirCount) {121 basePath = path.join(taskDirPath, testDirs[0]);122 dirs = fs.readdirSync(basePath);123 dirNameRE = RUN_DIR_NAME_RE;124 if (!dirs || !dirs.length || dirs.length !== runDirCount)125 return false;126 }127 else {128 basePath = taskDirPath;129 dirs = testDirs;130 dirNameRE = TEST_DIR_NAME_RE;131 }132 return dirs.every(function (dir) {133 if (!dirNameRE.test(dir))134 return false;135 dirPath = path.join(basePath, dir);136 return checkTestDir(dirPath, forError, expectedSubDirCount, expectedScreenshotCount);137 });138};139exports.removeScreenshotDir = function () {140 if (isDirExists(SCREENSHOTS_PATH))141 del(SCREENSHOTS_PATH);...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...39 if (typeof mode === 'undefined') {40 // 511 === 077741 mode = 511 & ~process.umask();42 }43 if (isDirExists(path)) return;44 path45 .replace(/\\/g, '/')46 .split('/')47 .reduce(function(prev, next) {48 if (prev && !isDirExists(prev)) {49 fs.mkdirSync(prev, mode);50 }51 return prev + '/' + next;52 });53 if (!isDirExists(path)) {54 fs.mkdirSync(path, mode);55 }56}57const readFileMd5 = url => {58 return new Promise(resolve => {59 let md5sum = crypto.createHash('md5');60 let stream = fs.createReadStream(url);61 stream.on('data', function(chunk) {62 md5sum.update(chunk);63 });64 stream.on('end', function() {65 let fileMd5 = md5sum.digest('hex');66 resolve(fileMd5);67 });...

Full Screen

Full Screen

fileAttributes.js

Source:fileAttributes.js Github

copy

Full Screen

1const fse = require('fs-extra');2const fs = require('fs');3const fileInfo = (filename) => {4 var stats = {};5 try {6 stats = fse.statSync(filename);7let isDirExists = fs.lstatSync(filename).isDirectory()8 var fileBase64;9 var is_folder = false10 //console.log("Dir exists.",isDirExists);11 if (isDirExists) {12 fileBase64 = ""13 is_folder = true14 } else {15 const fileContents = fse.readFileSync(filename);16 fileBase64 = fileContents.toString('base64');17 }18 stats['data'] = fileBase6419 stats['file_path'] = filename20 stats['is_folder'] = is_folder21 return stats22}23catch (e) {24 console.log("File does not exist.-----with error: ",e);25 return null26}27}...

Full Screen

Full Screen

helpers.js

Source:helpers.js Github

copy

Full Screen

1import fs from 'fs';2import path from 'path';3import { fileURLToPath } from 'url';4const __filename = fileURLToPath(import.meta.url);5const __dirname = path.dirname(__filename);6export const createTempDirectoryIfNotExists = () => {7 const tempPath = path.join(__dirname, '..', 'temp');8 const isDirExists = fs.existsSync(tempPath);9 if (!isDirExists) {10 fs.mkdirSync(tempPath, { recursive: true });11 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5 const articleHeader = await Selector('.result-content').find('h1');6 let headerText = await articleHeader.innerText;7});8test('My second test', async t => {9 .typeText('#developer-name', 'John Smith')10 .click('#submit-button');11 const articleHeader = await Selector('.result-content').find('h1');12 let headerText = await articleHeader.innerText;13});14test('My third test', async t => {15 .typeText('#developer-name', 'John Smith')16 .click('#submit-button');17 const articleHeader = await Selector('.result-content').find('h1');18 let headerText = await articleHeader.innerText;19});20test('My fourth test', async t => {21 .typeText('#developer-name', 'John Smith')22 .click('#submit-button');23 const articleHeader = await Selector('.result-content').find('h1');24 let headerText = await articleHeader.innerText;25});26test('My fifth test', async t => {27 .typeText('#developer-name', 'John Smith')28 .click('#submit-button');29 const articleHeader = await Selector('.result-content').find('h1');30 let headerText = await articleHeader.innerText;31});32test('My sixth test', async t => {33 .typeText('#developer-name', 'John Smith')34 .click('#submit-button');35 const articleHeader = await Selector('.result-content').find('h1');36 let headerText = await articleHeader.innerText;37});38test('My seventh test', async t => {39 .typeText('#developer-name', 'John Smith')40 .click('#submit-button');41 const articleHeader = await Selector('.result-content').find('h1

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button')5 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7test('Check if file exists', async t => {8 const fs = require('fs');9 .expect(fs.existsSync('test.js')).eql(true);10});11test('Check if directory exists', async t => {12 const fs = require('fs');13 .expect(fs.existsSync('Folder')).eql(true);14});15test('Check if file exists', async t => {16 const fs = require('fs');17 .expect(fs.existsSync('test.js')).eql(true);18});19test('Check if directory exists', async t => {20 const fs = require('fs');21 .expect(fs.existsSync('Folder')).eql(true);22});23test('Check if file exists', async t => {24 const fs = require('fs');25 .expect(fs.existsSync('test.js')).eql(true);26});27test('Check if directory exists', async t => {28 const fs = require('fs');29 .expect(fs.existsSync('Folder')).eql(true);30});31test('Check if file exists', async t => {32 const fs = require('fs');33 .expect(fs.existsSync('test.js')).eql(true);34});35test('Check if directory exists', async t => {36 const fs = require('fs');37 .expect(fs.existsSync('Folder')).eql(true);38});

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3});4import { Selector } from 'testcafe';5import { isDirExists } from 'testcafe';6test('My first test', async t => {7});8import { Selector } from 'testcafe';9import { isDirExists } from 'testcafe';10test('My first test', async t => {11});12import { Selector } from 'testcafe';13import { isDirExists } from 'testcafe';14test('My first test', async t => {15});16import { Selector } from 'testcafe';17import { isDirExists } from 'testcafe';18test('My first test', async t => {19});20import { Selector } from 'testcafe';21import { isDirExists } from 'testcafe';22test('My first test', async t => {23});24import { Selector } from 'testcafe';25import { isDirExists } from 'testcafe';26test('My first test', async t => {27});28import { Selector } from 'testcafe';29import { is

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2test('My first test', async t => {3 .setFilesToUpload('input[type="file"]', [4 ]);5});6test('My second test', async t => {7 .setFilesToUpload('input[type="file"]', [8 ]);9});10test('My third test', async t => {11 .setFilesToUpload('input[type="file"]', [12 ]);13});14test('My fourth test', async t => {15 .setFilesToUpload('input[type="file"]', [16 ]);17});18test('My fifth test', async t => {19 .setFilesToUpload('input[type="file"]', [20 ]);21});22test('My sixth test', async t => {23 .setFilesToUpload('input[type="file"]', [24 ]);25});26test('My seventh test', async t => {27 .setFilesToUpload('input[type="file"]', [28 ]);29});30test('My eighth test', async t => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector } from 'testcafe';2import { isDirExists } from 'testcafe-file-helpers';3test('My first test', async t => {4 .typeText('#developer-name', 'John Smith')5 .click('#submit-button');6 const articleHeader = await Selector('.result-content').find('h1');7 let headerText = await articleHeader.innerText;8 console.log(headerText);9 let isDir = await isDirExists('C:\\testcafe');10 console.log(isDir);11});12const fs = require('fs');13at Module._compile (module.js:439:25)14at Object.Module._extensions..js (module.js:474:10)15at Module.load (module.js:356:32)16at Function.Module._load (module.js:312:12)17at Module.require (module.js:364:17)18at require (module.js:380:17)19at Object.<anonymous> (C:\Users\user\Documents\testcafe\node_modules\testcafe-file-helpers\lib\fs-helpers.js:1:1)20at Module._compile (module.js:456:26)21at Object.Module._extensions..js (module.js:474:10)22at Module.load (module.js:356:32)231/1 failed (2s)

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Selector, t } from 'testcafe';2import fs from 'fs';3import { resolve } from 'path';4import { ClientFunction } from 'testcafe';5import { getTestRun } from 'testcafe';6import { Selector } from 'testcafe';7const testController = await getTestRun();8const downloadFolder = './downloads';9const getDownloadedFileName = ClientFunction(() => {10 return document.getElementById('downloadedFileName').value;11});12test('Download File', async t => {13 .click('#downloadFile')14 .expect(getDownloadedFileName()).eql('test.pdf');15 await t.expect(fs.existsSync(resolve(downloadFolder, 'test.pdf'))).ok();16});17import { Selector, t } from 'testcafe';18import fs from 'fs';19import { resolve } from 'path';20import { ClientFunction } from 'testcafe';21import { getTestRun } from 'testcafe';22import { Selector } from 'testcafe';23const testController = await getTestRun();24const downloadFolder = './downloads';25const getDownloadedFileName = ClientFunction(() => {26 return document.getElementById('downloadedFileName').value;27});28test('Download File', async t => {29 .click('#downloadFile')30 .expect(getDownloadedFileName()).eql('test.pdf');31 await t.expect(fs.existsSync(resolve(downloadFolder, 'test.pdf'))).ok();32});33import { Selector, t } from 'testcafe';34import fs from 'fs';35import { resolve } from 'path';36import { ClientFunction } from 'testcafe';37import { getTestRun } from 'testcafe';38import { Selector } from 'testcafe';39const testController = await getTestRun();40const downloadFolder = './downloads';41const getDownloadedFileName = ClientFunction(() => {42 return document.getElementById('downloadedFileName').value;43});44test('

Full Screen

Using AI Code Generation

copy

Full Screen

1import { TestcafeFileUtils } from 'testcafe-file-utils';2const path = require('path');3const fileUtils = new TestcafeFileUtils();4const directoryPath = path.resolve(__dirname, './');5await fileUtils.isDirExists(directoryPath).then((result) => {6 console.log(result);7}).catch((error) => {8 console.log(error);9});10import { TestcafeFileUtils } from 'testcafe-file-utils';11const path = require('path');12const fileUtils = new TestcafeFileUtils();13const directoryPath = path.resolve(__dirname, './');14await fileUtils.isDirExists(directoryPath).then((result) => {15 console.log(result);16}).catch((error) => {17 console.log(error);18});19import { TestcafeFileUtils } from 'testcafe-file-utils';20const path = require('path');21const fileUtils = new TestcafeFileUtils();22const filePath = path.resolve(__dirname, './file.txt');23await fileUtils.isFileExists(filePath).then((result) => {24 console.log(result);25}).catch((error) => {26 console.log(error);27});28import { TestcafeFileUtils } from 'testcafe-file-utils';29const path = require('path');30const fileUtils = new TestcafeFileUtils();31const filePath = path.resolve(__dirname, './file.txt');32await fileUtils.isFileExists(filePath).then((result) => {33 console.log(result);34}).catch((error) => {35 console.log(error);36});37import { TestcafeFileUtils } from 'testcafe-file-utils';38const path = require('path');39const fileUtils = new TestcafeFileUtils();40const filePath = path.resolve(__dirname, './file.txt');41await fileUtils.isFileExists(filePath).then((result) => {42 console.log(result);43}).catch((error) => {44 console.log(error);45});46import { Testca

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcafe automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful