How to use fsExtra.mkdir method in Cypress

Best JavaScript code snippet using cypress

util.js

Source:util.js Github

copy

Full Screen

1'use strict';2const BaseController = require('./base');3const svgCaptcha = require('svg-captcha');4const fsextra = require('fs-extra');5const path = require('path');6const qiniu = require('qiniu');7const fs = require('fs');8const sizeOf = require('image-size');9class UtilController extends BaseController {10 async getCaption() {11 const { ctx } = this;12 const captcha = svgCaptcha.create({13 size: 4,14 noise: 5,15 width: 100,16 height: 40,17 });18 ctx.session.captcha = captcha.text;19 ctx.response.type = 'image/svg+xml';20 ctx.body = captcha.data;21 }22 async sendcode() {23 const { ctx } = this;24 const { email } = ctx.request.query;25 // 取4位随机验证码26 const code = Math.random().toString().slice(2, 6);27 ctx.session.emailcode = code;28 const subject = 'qyuan验证码';29 const text = '';30 const html = `<h1>来自qyuan社区</h1><a href="#">${code}</a>`;31 const hasSend = await this.service.tools.sendMail(email, subject, text, html);32 if (hasSend) {33 this.message('邮箱验证码发送成功');34 } else {35 this.error('邮箱验证码发送失败');36 }37 }38 // 七牛token39 async qiniuToken() {40 const accessKey = 'opab2PsghpFhBKHSx98L1RdbXcj77UxNHWI5p0C1';41 const secretKey = 'Xg0OU1Ga40r__PZPx3mkFG9TofRbl0Xv_QYhzSMg';42 const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);43 const options = {44 scope: 'qyuan', // 存储空间名字45 expires: 7200, // 有效期46 returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',47 };48 const putPolicy = new qiniu.rs.PutPolicy(options);49 const uploadToken = putPolicy.uploadToken(mac);50 this.success(uploadToken);51 }52 // 文件直接上传53 async updateSmailFile() {54 const { ctx } = this;55 const file = ctx.request.files[0];56 const { hash } = ctx.request.body;57 console.log(hash, file);58 // 替换图片功能,如不需要替换可删除59 if (ctx.request.body.oldImage) {60 const oldImage = ctx.request.body.oldImage;61 await fsextra.remove(this.config.UPLOAD_DIR + '/' + oldImage, err => {62 if (err) {63 return console.error(err);64 }65 });66 }67 // 将文件临时地址移动到目标地址68 const ext = file.filename.split('.').pop();69 const fileHashName = hash + '.' + ext;70 await fsextra.move(file.filepath, this.config.UPLOAD_DIR + '/' + fileHashName);71 // 个别需求:获取图片宽高 传递给前端72 const dimensions = sizeOf(`./app/public/${fileHashName}`);73 this.success({74 url: `/public/${fileHashName}`,75 height: dimensions.height,76 width: dimensions.width,77 name: fileHashName,78 });79 }80 /**81 * 删除文件82 * @params name83 */84 async deleteSmailFile() {85 const { ctx } = this;86 const { name } = ctx.request.query;87 console.log('删除', name);88 if (!name) {89 this.error('删除失败');90 return;91 }92 await fsextra.remove(this.config.UPLOAD_DIR + '/' + name, err => {93 if (err) {94 return console.error(err);95 }96 });97 this.message('删除成功');98 }99 // 切片上传100 async updateFile() {101 // 报错102 // if(Math.random() > 0.5){103 // return this.ctx.status = 500104 // }105 const { ctx } = this;106 const file = ctx.request.files[0];107 const { name, hash } = ctx.request.body;108 console.log(name);109 // 以hash命名文件夹110 const chunkPath = path.resolve(this.config.UPLOAD_DIR, hash);111 // 是否存在该文件夹,不存在创建112 if (!fsextra.existsSync(chunkPath)) {113 fsextra.mkdir(chunkPath);114 }115 // 移动chunk文件到hash文件夹下116 await fsextra.move(file.filepath, `${chunkPath}/${name}`);117 this.message('chunk上传成功');118 }119 // 合并文件120 async mergeFile() {121 const { ext, hash, size } = this.ctx.request.body;122 // 真实文件路径123 const filePath = path.resolve(this.config.UPLOAD_DIR, `${hash}.${ext}`);124 await this.ctx.service.tools.mergeFile(filePath, hash, size);125 this.success({126 url: `/public/${hash}.${ext}`,127 });128 }129 /**130 * @summary 检查文件是否存在或存在的切片131 * @response {uploaded,uploadedList}132 */133 async checkfile() {134 const { ext, hash } = this.ctx.request.body;135 console.log(ext, hash);136 const filePath = path.resolve(this.config.UPLOAD_DIR, `${hash}.${ext}`);137 // 文件已存在138 let uploaded = false;139 // 切片已存在140 let uploadedList = [];141 if (fsextra.existsSync(filePath)) {142 uploaded = true;143 } else {144 // 返回已上传的所有切片名字145 const chunkPath = path.resolve(this.config.UPLOAD_DIR, hash);146 uploadedList = await this.getUploadedList(chunkPath);147 }148 this.success({149 uploaded,150 uploadedList,151 });152 }153 /**154 * @summary 返回已上传所有切片名字155 */156 async getUploadedList(dirPath) {157 return fsextra.existsSync(dirPath)158 ? (await fsextra.readdir(dirPath)).filter(name => name[0] !== '.') // 除去隐藏文件,其余切片都返回159 : []; // 文件夹不存在返回空160 }161 /**162 * 下载文件流163 */164 async download() {165 const filePath = path.resolve(__dirname, '../public/a0ce40201caca1835fdc86c3fe05a24f.jpg');166 // 创建读取流167 const readStream = fs.createReadStream(filePath);168 console.log('读取流', readStream);169 // // 写入170 // const writeStream = fs.createWriteStream(path.resolve(__dirname, '../public/1.jpg'));171 // // 管道流从输入定位到输出172 // readStream.pipe(writeStream);173 this.ctx.set('Content-Type', 'application/octet-stream');174 this.ctx.body = readStream;175 }176}...

Full Screen

Full Screen

file.js

Source:file.js Github

copy

Full Screen

1const multer = require("multer");2const fs = require("fs");3const fsextra = require("fs-extra");4const mime = require("mime");5const AppErrorHandler = require("./error-handler");6const logger = require("./winston");7var storage = multer.diskStorage({8 destination: function (req, file, cb) {9 //dynamic destination for different elements10 var file_type = `${file.mimetype.split("/")[0]}`;11 var destination = `${process.env.APP_BASE_PATH}/public/uploads/${file_type}`;12 var stat = null;13 try {14 stat = fs.statSync(destination);15 } catch (err) {16 //to make directory if not found17 fs.mkdirSync(destination);18 }19 if (stat && !stat.isDirectory()) {20 throw new Error("Directory cannot be created");21 }22 req.file_destination = file_type;23 cb(null, destination);24 },25 filename: function (req, file, cb) {26 let req_field = file.fieldname;27 //check element to choose image name28 var file_name = Date.now() + "_" + file.originalname;29 //reassign request upload field to file_name30 req.body[req_field] = `${req.file_destination}/${file_name}`;31 cb(null, file_name);32 },33});34const upload = multer({ storage: storage });35function converBase64toBlob(content, contentType) {36 contentType = contentType || "";37 var sliceSize = 512;38 var byteCharacters = window.atob(content); //method which converts base64 to binary39 var byteArrays = [];40 for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {41 var slice = byteCharacters.slice(offset, offset + sliceSize);42 var byteNumbers = new Array(slice.length);43 for (var i = 0; i < slice.length; i++) {44 byteNumbers[i] = slice.charCodeAt(i);45 }46 var byteArray = new Uint8Array(byteNumbers);47 byteArrays.push(byteArray);48 }49 var blob = new Blob(byteArrays, {50 type: contentType,51 }); //statement which creates the blob52 return blob;53}54const base64ToImage = function (file_name, fields = []) {55 if (typeof fields == "string") {56 fields = [fields];57 }58 return [59 async (req, res, next) => {60 try {61 let base64Data = fields62 .map((item, i, array) => {63 let data = null;64 if (req.body[item] != undefined) {65 if (req.body[item] instanceof Array) {66 console.log("if");67 let images = req.body[item];68 req.body[item] = [];69 data = images.map((itm, i, arr) => {70 let image = convertBase64ToBuffer(itm);71 req.body[item].push(72 `${image.base_path}/${image.timestamp}_${file_name}.${image.extension}`73 );74 return image;75 });76 } else {77 console.log("else");78 data = convertBase64ToBuffer(req.body[item]);79 req.body[80 item81 ] = `${data.base_path}/${data.timestamp}_${file_name}.${data.extension}`;82 }83 }84 return data;85 })86 .filter((item) => item != null);87 var merged = [].concat.apply([], base64Data);88 merged.forEach(async (element) => {89 let dir = `${process.env.APP_BASE_PATH}public/uploads/${element.base_path}`;90 try {91 await fsextra.mkdir(dir);92 } catch (err) {93 if (err.code == "EEXIST") {94 logger.info(`DIRECTORY ALREADY EXISTS ${dir}`);95 } else {96 logger.info(err);97 }98 }99 let file_store_path = `${dir}/${element.timestamp}_${file_name}.${element.extension}`;100 await fsextra.writeFile(file_store_path, element.buffer, "utf8");101 });102 next();103 } catch (err) {104 new AppErrorHandler(res, err.message);105 }106 },107 ];108};109function convertBase64ToBuffer(ibuffer) {110 let matches = ibuffer.match(/^data:([A-Za-z-+.-/\/]+);base64,(.+)$/);111 let response = {};112 if (!(matches instanceof Array)) {113 throw new Error("Invalid base64 string");114 }115 if (matches.length !== 3) {116 throw new Error("Invalid base64 string");117 }118 response.type = matches[1];119 response.data = Buffer.from(matches[2], "base64");120 let imageBuffer = response.data;121 let type = response.type;122 let extension = mime.getExtension(type);123 let base_path = response.type.split("/")[0];124 return {125 base_path: base_path,126 timestamp: Date.now(),127 type: type,128 extension: extension,129 buffer: imageBuffer,130 };131}132const FileUpload = {133 upload,134 base64ToImage,135};...

Full Screen

Full Screen

gameService.js

Source:gameService.js Github

copy

Full Screen

1import path from "path"2import { MongoMemoryServer } from "mongodb-memory-server-core"3import { MongoClient, ObjectId } from "mongodb"4import express from "express"5import morgan from "morgan"6import fsextra from "fs-extra"7const GAME = "game"8const DB_PATH = path.join(process.cwd(), GAME, "db")9fsextra.existsSync(DB_PATH) || (await fsextra.mkdir(DB_PATH))10const DB_BINARY = path.join(process.cwd(), GAME, "db-binary")11fsextra.existsSync(DB_BINARY) || (await fsextra.mkdir(DB_BINARY))12const mongod = await MongoMemoryServer.create({13 instance: {14 dbPath: DB_PATH,15 },16 binary: {17 downloadDir: DB_BINARY,18 },19})20export const uri = mongod.getUri()21const client = new MongoClient(uri)22await client.connect()23const db = await client.db(GAME)24const games = db.collection("games")25console.log(`MongoDB running on URI ${uri}`)26const app = express()27app.use(express.json()) // for parsing application/json28app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded29app.use(morgan("dev"))30app.get("/game", async (req, res) => {31 const game = await games.findOne({32 _id: new ObjectId(req.query.id),33 })34 res.json(game)35})36app.post("/game", async (req, res) => {37 const { dimensions, snakeCoordinates, snakeDirection, treatCoordinate } =38 req.body39 const result = await games.insertOne({40 dimensions,41 snakeCoordinates,42 snakeDirection,43 treatCoordinate,44 collectedTreats: 0,45 gameOver: false,46 })47 res.send(result.insertedId.toString())48})49const OFFSET_LOOKUP = {50 UP: [0, -1],51 DOWN: [0, 1],52 LEFT: [-1, 0],53 RIGHT: [1, 0],54}55app.put("/game", async (req, res) => {56 const {57 snakeDirection,58 snakeCoordinates: pastSnakeCoordinates,59 gameOver,60 } = await games.findOne({61 _id: new ObjectId(req.body.id),62 })63 if (!gameOver) {64 console.log(`Advancing snake in ${snakeDirection} direction`)65 const lastHead = pastSnakeCoordinates[pastSnakeCoordinates.length - 1]66 const offset = OFFSET_LOOKUP[snakeDirection]67 const newHead = [lastHead[0] + offset[0], lastHead[1] + offset[1]]68 const session = client.startSession()69 try {70 await session.withTransaction(async () => {71 await games.updateOne(72 { _id: new ObjectId(req.body.id) },73 {74 $pop: { snakeCoordinates: -1 },75 }76 )77 await games.updateOne(78 { _id: new ObjectId(req.body.id) },79 {80 $push: {81 snakeCoordinates: newHead,82 },83 }84 )85 const game = await games.findOne({ _id: new ObjectId(req.body.id) })86 const { snakeCoordinates } = game87 res.json(snakeCoordinates)88 })89 } finally {90 await session.endSession()91 }92 } else {93 res.json({ gameOver: true })94 }95})96app.put("/endGame", async (req, res) => {97 await games.updateOne(98 { _id: new ObjectId(req.body.id) },99 { $set: { gameOver: true } }100 )101 console.log(`Game over ${req.body.id}`)102 res.json({ gameOver: true })103})104app.put("/snake-direction", async (req, res) => {105 res.json(106 await games.updateOne(107 { _id: new ObjectId(req.body.id) },108 {109 $set: {110 snakeDirection: req.body.snakeDirection,111 },112 }113 )114 )115})116app.post("/treat", async (req, res) => {117 const { snakeDirection, snakeCoordinates } = await games.findOne({118 _id: new ObjectId(req.body.id),119 })120 const extraX = snakeCoordinates[0][0] - OFFSET_LOOKUP[snakeDirection][0]121 const extraY = snakeCoordinates[0][1] - OFFSET_LOOKUP[snakeDirection][1]122 res.json(123 await games.updateOne(124 { _id: new ObjectId(req.body.id) },125 {126 $inc: {127 collectedTreats: 1,128 },129 $set: {130 treatCoordinate: req.body.treatCoordinate,131 },132 $push: {133 snakeCoordinates: {134 $each: [[extraX, extraY]],135 $position: 0,136 },137 },138 }139 )140 )141})142const PORT = process.env.PORT || 3000143app.listen(PORT, () =>144 console.log(`Game service listening at http://localhost:${PORT}`)145)146process.on("exit", async () => {147 await client.close()148 await mongod.stop()...

Full Screen

Full Screen

uploadTo145.js

Source:uploadTo145.js Github

copy

Full Screen

1const archiver = require('archiver');2const fs = require("fs");3const path = require("path");4const FTPS = require('ftps');5const unzip = require('extract-zip');6const fsextra = require('fs-extra')7// 大厅FTP参数8const hallFtpOpt = {9 host: "192.168.2.145",10 port: 21,11 username: "lanwan",12 password: "Lanwanhudong@20191010"13}14const defaultGame = "10017";15const archiverPromise = async (dirpath, zippath) => {16 if (fs.existsSync(zippath)) {17 fs.unlinkSync(zippath);18 }19 if (!fs.existsSync(dirpath)) {20 console.log('目录不存在' + dirpath);21 return;22 }23 return new Promise((resolve, reject) => {24 let output = fs.createWriteStream(zippath);25 let archive = archiver('zip', {26 zlib: {27 level: 928 }29 });30 output.on('close', function () {31 console.log(archive.pointer() + ' total bytes');32 console.log('archiver has been finalized and the output file descriptor has closed.');33 resolve(zippath);34 });35 output.on('end', function () {36 console.log('Data has been drained');37 });38 archive.on('warning', function (err) {39 console.log("archive warning", err)40 if (err.code === 'ENOENT') { } else { }41 });42 archive.on('error', function (err) {43 console.log("archive error", err)44 reject(err);45 });46 archive.pipe(output);47 archive.directory(dirpath, false);48 archive.finalize();49 })50}51let main = async function () {52 let WORKSPACE = path.dirname(__dirname);53 fsextra.removeSync(path.join(WORKSPACE, "temp", "resoutput.zip"));54 await archiverPromise(path.join(WORKSPACE, "temp", "resoutput"), path.join(WORKSPACE, "temp", "resoutput.zip"));55 console.log("生成", path.join(WORKSPACE, "temp", "resoutput.zip"));56 if (!fsextra.existsSync(path.join(WORKSPACE, "nativeapp", "hallgames"))) {57 fsextra.mkdirSync(path.join(WORKSPACE, "nativeapp", "hallgames"));58 }59 let ftps = new FTPS(hallFtpOpt);60 ftps.raw(`rm -rf ios/assetspatch`);61 ftps.put(path.join(WORKSPACE, "temp", "resoutput.zip"), `ios/assetspatch.zip`)62 ftps.mirror({63 remoteDir: `ios/assetspatch`,64 localDir: path.join(WORKSPACE, "temp", "resoutput"),65 upload: true,66 options: "--allow-chown"67 });68 console.log("准备上传到 " + hallFtpOpt.host + " ios/assetspatch")69 ftps.raw(`rm -rf android/assetspatch`);70 ftps.put(path.join(WORKSPACE, "temp", "resoutput.zip"), `android/assetspatch.zip`)71 ftps.mirror({72 remoteDir: `android/assetspatch`,73 localDir: path.join(WORKSPACE, "temp", "resoutput"),74 upload: true,75 options: "--allow-chown"76 });77 let zipgamefilepath = path.join(WORKSPACE, "nativeapp", "hallgames", defaultGame + ".zip");78 fsextra.removeSync(zipgamefilepath);79 ftps.get(`hallgames/${defaultGame}.zip`, zipgamefilepath);80 console.log("准备上传到 " + hallFtpOpt.host + " android/assetspatch")81 await new Promise((resolve, reject) => {82 ftps.exec(function (err, res) {83 if (err) {84 console.log(res);85 reject(err)86 } else {87 console.log(res);88 resolve(res);89 }90 });91 });92 unzip(zipgamefilepath, { dir: path.join(path.dirname(zipgamefilepath), defaultGame) }, () => {93 fsextra.removeSync(zipgamefilepath);94 })95}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const fs = require('fs')2const http = require('http');3const path = require('path')4const cp = require('child_process');5const _ = require("underscore");6const open = require("open");7const watch = require('gulp-watch');8const express = require('express')9const webpack = require('webpack')10const fsextra = require('fs-extra')11const util = require('../util')12const execDebug = require('../debug/index')13//https://github.com/webpack/webpack-dev-middleware#usage14const webpackDevMiddleware = require("webpack-dev-middleware");15const webpacHotMiddleware = require('webpack-hot-middleware')16const killOccupied = require('../kill.occupied')17const convert = require('../convert/index')18const app = express()19const buildName = process.argv[process.argv.length - 1] || 'webpack-full-dev'20const config = require('../config')(buildName)21const port = config.port22/**23 * 转化24 * 1 数据 db-json25 * 2 文件 svg-js26 */27convert(config.templateDirPath)28//清理temp目录29fsextra.removeSync(config.assetsRootPath)30fsextra.mkdirSync(config.assetsRootPath)31const webpackConfig = require('./webpack.config')(config)32/**33 * eslint34 * https://segmentfault.com/a/1190000008575829?utm_source=itdadao&utm_medium=referral35 **/36if (config.eslint.launch) {37 webpackConfig.module.rules.push({38 test: /\.js$/,39 enforce: "pre", //在babel-loader对源码进行编译前进行lint的检查40 include: config.eslint.includePath,41 exclude: /node_modules/,42 use: [{43 loader: "eslint-loader",44 options: {45 formatter: require("eslint-friendly-formatter")46 }47 }]48 })49}50const compiler = webpack(webpackConfig)51const devMiddleware = webpackDevMiddleware(compiler, {52 //The path where to bind the middleware to the server.53 //In most cases this equals the webpack configuration option output.publicPath54 publicPath: webpackConfig.output.publicPath,55 //Output options for the stats. See node.js API.56 //http://webpack.github.io/docs/node.js-api.html57 stats: {58 //With console colors59 colors: true,60 //add chunk information61 chunks: false62 }63})64//Webpack热重载连接服务器65//https://github.com/glenjamin/webpack-hot-middleware66//Add webpack-hot-middleware attached to the same compiler instance67const hotMiddleware = webpacHotMiddleware(compiler)68// force page reload when html-webpack-plugin template changes69compiler.plugin('compilation', (compilation) => {70 //https://github.com/ampedandwired/html-webpack-plugin71 compilation.plugin('html-webpack-plugin-after-emit', (data, cb) => {72 hotMiddleware.publish({73 action: 'reload'74 })75 cb()76 })77})78// serve webpack bundle output79app.use(devMiddleware)80// enable hot-reload and state-preserving81// compilation error display82app.use(hotMiddleware)83app.use('/src', express.static('src'));84app.use('/css', express.static('template/css'));85app.use('/images', express.static('template/images'));86app.use('/content', express.static('template/content'));87let first = true88watch(path.join(config.assetsRootPath, config.assetsName), () => {89 if (config.openBrowser && first) {90 open("http://localhost:" + port)91 first = false92 }93 if (config.debug.launch) {94 execDebug(config)95 }96})97killOccupied(port, () => {98 app.listen(port, (err) => {99 if (err) {100 util.log(err)101 return102 }103 util.log('Listening at http://localhost:' + port + '\n')104 })...

Full Screen

Full Screen

script.js

Source:script.js Github

copy

Full Screen

1var path = require('path');2var os = require('os');3var fsextra = require('fs-extra');4var cp = require('child_process');5var exec = cp.exec;6var sqawn = cp.sqawn;7var global = {};8global.tests_dir = fsextra.realpathSync('.');9var required_file_win_linux = fsextra.readdirSync(path.dirname(process.execPath));10var required_file_win = required_file_win_linux;11var required_file_linux = required_file_win_linux;12var required_file_macox = [13 'node-webkit.app'14];15var source_file = ['index.html', 'package.json'];16var exec_root = path.dirname(process.execPath);17var required_file;18if (os.platform() == 'win32') {19 required_file = required_file_win;20}21if (os.platform() == 'linux') {22 required_file = required_file_linux;23}24if (os.platform() == 'darwin') {25 required_file = required_file_macox;26 if (~exec_root.indexOf("Helper.app"))27 exec_root = path.join(exec_root, '..', '..', '..')28 exec_root = path.normalize(29 path.join(exec_root, '..', '..', '..'));30}31exports.getExecPath = function() {32 if (os.platform() == 'win32') {33 return path.join('tmp-nw', 'nw.exe');34 }35 if (os.platform() == 'linux') {36 return path.join('tmp-nw', 'nw');37 }38 if (os.platform() == 'darwin') {39 return path.join('tmp-nw', 'node-webkit.app', 'Contents', 'MacOS', 'node-webkit');40 }41}42function copyExecFiles(done) {43 fsextra.mkdir('tmp-nw', function(err) {44 if(err && err.code !== 'EEXIST') throw err;45 var files_done = 0;46 for (var i in required_file) {47 var src_file = path.join(exec_root, required_file[i]);48 var dst_file = path.join('tmp-nw', required_file[i]);49 fsextra.copySync(src_file, dst_file);50 }51 done();52 });53}54exports.copySourceFiles = function(folder) {55 if (folder == undefined)56 folder = 'start_app';57 fsextra.createReadStream(global.tests_dir + '/' + folder + '/index.html').pipe(58 fsextra.createWriteStream('tmp-nw/index.html'));59 fsextra.createReadStream(global.tests_dir + '/' + folder + '/package.json').pipe(60 fsextra.createWriteStream('tmp-nw/package.json'));61}62exports.zipSourceFiles = function(callback) {63 exec('python '+path.join(global.tests_dir, 'zip.py'));64 setTimeout(callback, 2000);65}66exports.makeExecuableFile = function() {67 if (os.platform() == 'win32') {68 cp.exec('copy /b nw.exe+app.nw app.exe', {cwd: './tmp-nw/'});69 }70 if (os.platform() == 'linux') {71 cp.exec('cat nw app.nw > app && chmod +x app', {cwd: './tmp-nw/'});72 }73}...

Full Screen

Full Screen

development.js

Source:development.js Github

copy

Full Screen

1require('draftLog')(console)2const chalk = require('chalk')3const childProcess = require('child_process')4const fsextra = require('fs-extra')5console.log()6console.log(chalk.white.bold.bgMagenta(" Intendant - Development "))7console.log()8const configurations = require('../intendant.module.json')9const main = async () => {10 let update = console.draft(chalk.white.bold.bgYellow(" >> ") + chalk(""))11 update(chalk.white.bold.bgYellow(" >> ") + chalk(" Delete cache "))12 if(fsextra.existsSync("./development")) {13 fsextra.removeSync("./development")14 }15 fsextra.mkdirSync("./development")16 fsextra.copySync("./template","./development")17 18 let newPackage = fsextra.readJSONSync("./development/package.json")19 update(chalk.white.bold.bgYellow(" >> ") + chalk(" Insert tmp dependencies "))20 for (let indexConfiguration = 0; indexConfiguration < configurations.length; indexConfiguration++) {21 let configuration = configurations[indexConfiguration]22 let pConfiguration = fsextra.readJSONSync(configuration + "/builds/package.json")23 for (let key in pConfiguration.dependencies) {24 newPackage.dependencies[key] = pConfiguration.dependencies[key]25 }26 }27 28 fsextra.writeJSONSync("./development/package.json",newPackage)29 update(chalk.white.bold.bgYellow(" >> ") + chalk(" Install dependencies "))30 await childProcess.execSync("cd development && npm install")31 update(chalk.white.bold.bgYellow(" >> ") + chalk(" Insert build sources"))32 for (let indexConfiguration = 0; indexConfiguration < configurations.length; indexConfiguration++) {33 let configuration = configurations[indexConfiguration]34 let pConfiguration = fsextra.readJSONSync(configuration + "/builds/package.json")35 fsextra.mkdirSync("./development/node_modules/" + pConfiguration.name,{recursive:true})36 fsextra.copySync(configuration + "/builds","./development/node_modules/" + pConfiguration.name)37 }38 if(fsextra.existsSync("./development/intendant.db.dev")) {39 fsextra.copyFileSync("./development/intendant.db.dev","./development/intendant.db")40 }41 update(chalk.white.bold.bgGreen(" >> ") + chalk("") + chalk.bold.green(" ✔"))42}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs-extra')2describe('My First Test', () => {3 it('Does not do much!', () => {4 expect(true).to.equal(true)5 })6 it('Creates a directory', () => {7 fs.mkdir('cypress/fixtures/MyDir')8 })9})

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.fsExtra.mkdir('/path/to/dir', { recursive: true })2cy.fsExtra.move('/path/to/old', '/path/to/new')3cy.fsExtra.outputFile('/path/to/file', 'data')4cy.fsExtra.outputJson('/path/to/file', { name: 'data' })5cy.fsExtra.outputJsonSync('/path/to/file', { name: 'data' })6cy.fsExtra.outputJSON('/path/to/file', { name: 'data' })7cy.fsExtra.outputJSONSync('/path/to/file', { name: 'data' })8cy.fsExtra.outputJsonSync('/path/to/file', { name: 'data' })9cy.fsExtra.outputFileSync('/path/to/file', 'data')10cy.fsExtra.pathExists('/path/to/file')11cy.fsExtra.pathExistsSync('/path/to/file')12cy.fsExtra.readFile('/path/to/file', 'utf8')13cy.fsExtra.readJson('/path/to/file')14cy.fsExtra.readJsonSync('/path/to/file')

Full Screen

Using AI Code Generation

copy

Full Screen

1fs.mkdir('cypress/screenshots/cypress/integration/screenshots', { recursive: true }, (err) => {2 if (err) throw err;3});4fs.mkdir('cypress/screenshots/cypress/integration/screenshots/failed', { recursive: true }, (err) => {5 if (err) throw err;6});7fs.mkdir('cypress/screenshots/cypress/integration/screenshots/passed', { recursive: true }, (err) => {8 if (err) throw err;9});10fs.mkdir('cypress/screenshots/cypress/integration/screenshots/skipped', { recursive: true }, (err) => {11 if (err) throw err;12});13Cypress.on('test:after:run', (test, runnable) => {14 if (test.state === 'failed') {15 fsExtra.move(`cypress/screenshots/${Cypress.spec.name}.png`, `cypress/screenshots/cypress/integration/screenshots/failed/${Cypress.spec.name}.png`, { overwrite: true })16 }17 else if (test.state === 'passed') {18 fsExtra.move(`cypress/screenshots/${Cypress.spec.name}.png`, `cypress/screenshots/cypress/integration/screenshots/passed/${Cypress.spec.name}.png`, { overwrite: true })19 }20 else if (test.state === 'skipped') {21 fsExtra.move(`cypress/screenshots/${Cypress.spec.name}.png`, `cypress/screenshots/cypress/integration/screenshots/skipped/${Cypress.spec.name}.png`, { overwrite: true })22 }23 })

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('fsExtra', () => {2 it('fsExtra.mkdir', () => {3 fsExtra.mkdir('cypress/screenshots')4 })5})6describe('fsExtra', () => {7 it('fsExtra.copy', () => {8 fsExtra.copy('cypress/screenshots', 'cypress/screenshots-copy')9 })10})11describe('fsExtra', () => {12 it('fsExtra.copySync', () => {13 fsExtra.copySync('cypress/screenshots', 'cypress/screenshots-copy')14 })15})16describe('fsExtra', () => {17 it('fsExtra.move', () => {18 fsExtra.move('cypress/screenshots-copy', 'cypress/screenshots-move')19 })20})21describe('fsExtra', () => {22 it('fsExtra.moveSync', () => {23 fsExtra.moveSync('cypress/screenshots-copy', 'cypress/screenshots-move')24 })25})26describe('fsExtra', () => {27 it('fsExtra.remove', () => {28 fsExtra.remove('cypress/screenshots-move')29 })30})31describe('fsExtra', () => {32 it('fsExtra.removeSync', () => {33 fsExtra.removeSync('cypress/screenshots-move')34 })35})36describe('fsExtra', () => {37 it('fsExtra.emptyDir', () => {38 fsExtra.emptyDir('cypress/screenshots')39 })40})

Full Screen

Using AI Code Generation

copy

Full Screen

1const fsExtra = require('fs-extra');2const path = require('path');3const dirPath = path.join(__dirname, './cypress/fixtures');4const dirName = 'uploads';5const dir = path.join(dirPath, dirName);6fsExtra.mkdirSync(dir);

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress 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