Best JavaScript code snippet using testcafe
convertXmltoJSON.js
Source:convertXmltoJSON.js
1const parseString = require('xml2js').parseString;2const fs = require('fs');3const ClinicalTrials = require('clinical-trials-gov');4let nctid = process.argv[2]; //nctid filename5const path = './XMLRes/';6const parseXML = (xml) => {7 let response;8 parseString(xml, {9 explicitArray: false,10 mergeAttrs: true,11 normalize: true,12 }, (err, result) => {13 if (!err) { 14 response = result;15 } else { throw err };16 });17 return response;18}19start();20function start() {21 getData(nctid, function(returnValue) {22 //For Windows23 nctid = nctid.split('.');24 nctid = nctid[0];25 //For Linux26 //nctid = nctid.split('/');27 //nctid = nctid[7].split('.');28 //nctid = nctid[0];29 30 fs.writeFile(path + nctid + '.json', returnValue.trim(), 'utf8', function (err) {31 if (err) {32 return console.log(err);33 }34 console.log("The file was saved!");35 process.exit();36 }); 37 });38}39function getData(nctid, callback) {40 fs.readFile(nctid, 'utf8', function(err, data) {41 if (!err) {42 let jsonO = {43 "results" : {44 },45 "Spots" : {46 },47 "SpotsC" : {48 }49 }50 let jsonspot = [];51 let jsonspotC = [];52 let json = [];53 json.push({54 });55 const main = async () => {56 57 let readFileContent = JSON.parse(JSON.stringify(parseXML(data)));58 readFileContent = readFileContent.clinical_study;59 //Results Array60 json[0]["id_info"] = readFileContent.id_info;61 json[0]["url"] = readFileContent.required_header.url; 62 json[0]["brief_title"] = readFileContent.brief_title;63 json[0]["official_title"] = readFileContent.official_title;64 json[0]["brief_summary"] = readFileContent.brief_summary;65 json[0]["location_countries"] = readFileContent.location_countries;66 json[0]["detailed_description"] = readFileContent.detailed_description;67 json[0]["last_update_submitted"] = readFileContent.last_update_submitted;68 json[0]["overall_contact"] = readFileContent.overall_contact;69 json[0]["eligibility"] = readFileContent.eligibility;70 json[0]["location"] = readFileContent.location;71 json[0]["intervention"] = readFileContent.intervention;72 json[0]["condition"] = readFileContent.condition;73 json[0]["phase"] = readFileContent.phase;74 json[0]["overall_status"] = readFileContent.overall_status;75 76 //Spot (city level) and SpotC (country level)77 let lengthdata = 1; let country = ''; let city = ''; let state = ''; 78 let name = '';79 let keyidx = 0;80 if (readFileContent.hasOwnProperty('location')) {81 if (typeof readFileContent.location.length === 'undefined')82 lengthdata = 1;83 else84 lengthdata = readFileContent.location.length;85 //console.log('location length: ' + lengthdata);86 for (let c = 0, len = lengthdata; c < len; c++) {87 88 if(lengthdata == 1) {89 if(readFileContent.location.facility.hasOwnProperty("name")) 90 name = readFileContent.location.facility.name;91 else92 name = '';93 if(readFileContent.location.facility.hasOwnProperty("address")) {94 95 if(readFileContent.location.facility.address.hasOwnProperty("country"))96 country = readFileContent.location.facility.address.country; 97 else98 country = '';99 100 if(readFileContent.location.facility.address.hasOwnProperty("state"))101 state = readFileContent.location.facility.address.state; 102 else 103 state = '';104 if(readFileContent.location.facility.address.hasOwnProperty("city"))105 city = readFileContent.location.facility.address.city; 106 else107 city = ''; 108 }109 if(name == '' && city != "")110 name = city;111 } else {112 if(readFileContent.location[c].facility.hasOwnProperty("name")) 113 name = readFileContent.location[c].facility.name;114 else115 name = '';116 if(readFileContent.location[c].facility.hasOwnProperty("address")) {117 118 if(readFileContent.location[c].facility.address.hasOwnProperty("country"))119 country = readFileContent.location[c].facility.address.country; 120 else 121 country = '';122 if(readFileContent.location[c].facility.address.hasOwnProperty("state"))123 state = readFileContent.location[c].facility.address.state; 124 else 125 state = '';126 if(readFileContent.location[c].facility.address.hasOwnProperty("city"))127 city = readFileContent.location[c].facility.address.city; 128 else129 city = '';130 }131 if(name == '' && city != "")132 name = city;133 }134 if(country == "Korea, Republic of") 135 country = "South Korea";136 if(country == "Macedonia, The Former Yugoslav Republic of")137 country = "Macedonia";138 if(country == "Former Serbia and Montenegro")139 country = "Serbia";140 if(country == "Iran, Islamic Republic of")141 country = "Iran";142 if(country == "Moldova, Republic of")143 country = "Moldova";144 if(country == "Korea, Democratic People's Republic of") 145 country = "South Korea";146 if(country == "Congo, The Democratic Republic of the") 147 country = "Congo";148 if(country == "Côte D'Ivoire")149 country = "Cote d'Ivoire";150 if(country == "Réunion")151 country = "Reunion";152 if(country == "Lao People's Democratic Republic")153 country = "Lao";154 if(country == "Syrian Arab Republic")155 country = "Syria";156 if(country == "Libyan Arab Jamahiriya")157 country = "Libya";158 state = state.replace(/[^A-Za-z 0-9]*/g, '').trim();159 city = city.replace(/[^A-Za-z 0-9]*/g, '').trim();160 console.log(readFileContent.id_info.nct_id + '|' + country + '|' + state + '|' + city);161 162 if(country != '') {163 164 //Get City Lat & Long Level165 let eror = 1; let eror_cnt = 1;166 let citylat = 0; let citylng = 0;167 let countrylat = 0; let countrylng = 0;168 while(eror != 0) { //redo if connection is failed169 console.log('City level:' + eror + '-' + eror_cnt);170 if(eror_cnt > 3) //2x times tried171 break;172 173 try {174 175 //Check if lat and lng already in DB176 let countrycity = await ClinicalTrials.CheckLatLongDB({city: city, state: state, country: country});177 countrycity = JSON.parse(countrycity);178 console.log('latlngDB:' + countrycity.length);179 if(countrycity.length > 0) {180 //Record exists in DB181 citylat = countrycity[0].city_lat;182 citylng = countrycity[0].city_lng;183 countrylat = countrycity[0].country_lat;184 countrylng = countrycity[0].country_lng;185 } else {186 //Record doesn't exists in DB187 //Get city lat lng from Heremap 188 let citylatlong = await ClinicalTrials.GetLatLongAPI({searchtext: city + ' ' + country});189 citylatlong = JSON.parse(citylatlong);190 if(citylatlong.Response.View.length > 0) {191 citylat = citylatlong.Response.View[0].Result[0].Location.DisplayPosition.Latitude;192 citylng = citylatlong.Response.View[0].Result[0].Location.DisplayPosition.Longitude;193 194 } 195 //Get country lat lng from Heremap 196 let countrylatlong = await ClinicalTrials.GetLatLongAPI({searchtext: country});197 countrylatlong = JSON.parse(countrylatlong);198 if(countrylatlong.Response.View.length > 0) {199 countrylat = countrylatlong.Response.View[0].Result[0].Location.DisplayPosition.Latitude;200 countrylng = countrylatlong.Response.View[0].Result[0].Location.DisplayPosition.Longitude;201 202 } 203 if(citylat == 0 && citylng ==0) {204 citylat = countrylat;205 citylng = countrylng;206 } 207 //Write to DB208 let insertcountrycity = await ClinicalTrials.InsertLatLongDB({city: city, citylat: citylat, citylng: citylng, state: state, country: country, countrylat: countrylat, countrylng: countrylng});209 //console.log('insertcountrycity:' + insertcountrycity);210 }211 212 countrylat = parseFloat(countrylat).toFixed(5);213 countrylng = parseFloat(countrylng).toFixed(5);214 citylat = parseFloat(citylat).toFixed(5);215 citylng = parseFloat(citylng).toFixed(5);216 console.log('City=> lat:' + citylat + ', lng:' + citylng);217 console.log('Country=> lat:' + countrylat + ', lng:' + countrylng);218 219 //Map Spots Detail: City Level220 jsonspot.push({221 key: keyidx,222 pos: citylng + ';' + citylat + ';0',223 tooltip: name,224 select: false,225 type: 'Success'226 });227 //Map Spots Detail: Country Level228 let found = jsonspotC.findIndex(r => r.pos === countrylng + ';' + countrylat + ';0');229 if(found == -1) { //lat & long not found230 jsonspotC.push({231 key: '1',232 pos: countrylng + ';' + countrylat + ';0',233 tooltip: country234 });235 } else { //lat & long found236 let total = parseInt(jsonspotC[found].key);237 total = total + 1;238 jsonspotC[found].key = total.toString();239 }240 eror = 0241 242 } catch (e) {243 eror = 1;244 eror_cnt++;245 console.log(e);246 }247 }248 keyidx++;249 }250 }251 }252 jsonO["results"] = json;253 jsonO["Spots"] = jsonspot;254 jsonO["SpotsC"] = jsonspotC;255 callback(JSON.stringify(jsonO)); 256 }257 main().catch(console.error);258 }259 });...
merge-files.js
Source:merge-files.js
...24 let imgArray = code.match(/"images\/[^"]*\.png"/gi)25 if(imgArray !== null){26 imgArray.map((imgcode) => {27 let p = baseDir+imgcode.replace(/"/g, '')28 let c = '"' + readFileContent(p, true) + '"'29 code = code.replace(imgcode, c)30 });31 }32 return code33}34/**35 * æ件æå
ï¼æ¼æ¥ï¼å½æ°36 * @param {*} path å
¥å£æ件çå°å37 */38const packFiles = function(path){39 /* éè¦è·åçæ件 */40 let content = readFileContent(path)41 let neededFiles = content.match(/{{3}[^}]*}{3}/g)42 /* è·åæ件å
容 */43 neededFiles.map((fileName) => {44 fileName = fileName.replace(/{|}/g, '')45 let fileCode46 if(fileName.match(/\.png$/) !== null){47 fileCode = readFileContent(fileName, true)48 }else{49 fileCode = readFileContent(fileName)50 }51 let fileRegex = new RegExp('{{{'+fileName.replace(/(\.|\/|\\)/g, '\$1')+'}}}', 'gi')52 if(fileName === 'Greasemonkey/DOM.html'){53 fileCode = imageTo64(fileCode, 'Greasemonkey/')54 }55 content = content.replace(fileRegex, fileCode)56 })57 return content58}59let Greasemonkey = packFiles('Greasemonkey/Script.js')60fs.writeFile(filedir+'dist/Link-Cleaner.user.js',61 Greasemonkey,62 (err) => {63 if (err) {64 return console.error(err);65 }66 })67/** å°ä¹¦ç¾ççæ **/68let bookmarklet = packFiles('Bookmarklet/Link-Cleaner.js')69const UglifyJS = require("uglify-es")70bookmarklet = UglifyJS.minify(bookmarklet, {71 mangle:false,72 output: {73 quote_style: 174 }75});76if(bookmarklet.error !== undefined){77 console.log(bookmarklet.error)78}79let bookmarkletCode = bookmarklet.code.replace(/\(\);$/, ')();').replace(/^!/, 'javascript:(')80fs.writeFile(filedir+'dist/Link-Cleaner.bookmarklet.js',81 bookmarkletCode,82 (err) => {83 if (err) {84 return console.error(err);85 }86 })87/** å°ä¹¦ç¾ç½®å
¥è¯´æææ¡£ä¸ **/88let readme = readFileContent('Pages/Readme.md').replace(/{{{theBookmarkletCode}}}/, bookmarkletCode)89fs.writeFile(filedir+'Readme.md',90 readme,91 (err) => {92 if (err) {93 return console.error(err);94 }...
db.js
Source:db.js
...38 }39 }40 // Logic to add data41 async save(data) {42 const items = await this.readFileContent();43 items.push(data);44 // Writing all records back to the file45 await promises.writeFile(this.filename, JSON.stringify(items, null, 2));46 return data;47 }48 async readFileContent() {49 try {50 // Read filecontents of the datastore51 const jsonRecords = await promises.readFile(this.filename, {52 encoding: "utf8",53 });54 // Parsing JSON records in JavaScript55 // object type records56 const objRecord = JSON.parse(jsonRecords);57 return objRecord;58 } catch (error) {59 console.error(`Got an error trying to read the file: ${error.message}`);60 }61 }62 async findByName(itemName) {63 const items = await this.readFileContent();64 const data = items.filter((item) => item.name === itemName);65 return data[0];66 }67 async findById(itemId) {68 const items = await this.readFileContent();69 const data = items.filter((item) => item.id === itemId);70 return data[0];71 }72 async find() {73 return await this.readFileContent();74 }75 async update(itemId, fields) {76 const itemToEdit = await this.findById(itemId);77 const data = await this.readFileContent();78 const items = data.filter((i) => i.id !== itemId);79 const updated = { ...itemToEdit, ...fields };80 items.push(updated);81 return await this.writeToFile(82 this.filename,83 JSON.stringify(items, null, 2)84 );85 }86 async delete(itemId) {87 const data = await this.readFileContent();88 const items = data.filter((i) => i.id !== itemId);89 return await this.writeToFile(90 this.filename,91 JSON.stringify(items, null, 2)92 );93 }94}...
fs-util.mocking-fs-extra.test.js
Source:fs-util.mocking-fs-extra.test.js
...33 const filePath = path.join(__dirname, ".test-resources", "sample-file.txt");34 fs.exists.mockResolvedValue(true);35 fs.readFile.mockResolvedValue("file content");36 // ACT37 const fileContent = await fsUtil.readFileContent(filePath);38 // ASSERT39 expect(fileContent).toBe("file content");40 });41 test("readFileContent: file does not exists", async () => {42 // ARRANGE43 const filePath = path.join(__dirname, ".test-resources", "sample-file.txt");44 fs.pathExists.mockResolvedValue(false);45 fs.readFile.mockResolvedValue("file content");46 // ACT47 const fileContent = await fsUtil.readFileContent(filePath);48 // ASSERT49 expect(fileContent).toBe(null);50 });51 test("readFileContent: throw error", async () => {52 // ARRANGE53 const filePath = path.join(__dirname, ".test-resources", "sample-file.txt");54 fs.pathExists.mockImplementation(() => {55 throw new Error();56 });57 fs.readFile.mockResolvedValue("file content");58 // ACT & ASSERT59 await expect(fsUtil.readFileContent(filePath)).rejects.toThrow();60 });61 test("copyEnsuringDest", async () => {62 // ACT63 await fsUtil.copyEnsuringDest("src", "dest");64 // ASSERT65 expect(fs.copy.mock.calls.length).toBe(1);66 });67 test("getTempFolder", async () => {68 // ARRANGE69 os.tmpdir.mockReturnValue("/temp/dir");70 // ACT71 await fsUtil.getTempFolder();72 // ASSERT73 expect(fs.mkdtemp.mock.calls[0][0]).toBe("/temp/dir");...
BooksRepo.js
Source:BooksRepo.js
2 constructor(){3 this.fse = require("fs-extra")4 this.catalogBookFilename = "../BookDonation/data/catalog.books.json"5 }6 async readFileContent(){7 let data = await this.fse.readFile(this.catalogBookFilename)8 let books = JSON.parse(data)9 return books;10 }11 async getBooks(bookName){12 let books = await this.readFileContent()13 let book = await books.find(b => b.title == bookName)14 if (book!=undefined)15 return book16 else17 return null18 }19 async getBooksWIthPageCountMoreThanX(pageCount){20 let books = await this.readFileContent()21 let filteredBook = await books.filter(b => b.pageCount > pageCount )22 return filteredBook23 }24 async getAuthorBooks(author){25 let books = await this.readFileContent()26 let authorBook = await books.filter(b => b.authors.indexOf(author)>=0)27 return authorBook28 }29 async getAuthorBookCount() {30 let books = await this.readFileContent()31 let authorCount = new Map()32 books.map(b => b.authors.map(author=>{33 if(authorCount.get(author)!=undefined)34 authorCount.set(author,authorCount.get(author)+1)35 else36 authorCount.set(author,1)37 }))38 return authorCount39 }40 async getBooksbyCatagory(category){41 let books = await this.readFileContent()42 let categorisedBooks = await books.filter(b => b.categories.indexOf(category)>=0)43 return categorisedBooks44 }45 async addBook(book){46 let books = await this.readFileContent()47 books.push(book)48 this.saveBooks(books)49 }50 async deleteBook(isbn){51 let books = await this.readFileContent()52 const index = books.findIndex(book=> book.isbn == isbn)53 books.splice(index, 1);54 this.saveBooks(books)55 }56 async updateBook(isbn, book){57 let books = await this.readFileContent()58 const index = books.findIndex(book=> book.isbn == isbn)59 books[index] = {...books[index], ...book};60 this.saveBooks(books)61 }62 async saveBooks(books){63 await this.fse.writeJson(this.catalogBookFilename, books)64 }65}66module.exports = new BooksRepo()67let Book = new BooksRepo();68//69// let obj = {70// name : "Abdulahi",71// age : 123,...
teamsRouter.js
Source:teamsRouter.js
...4const { readFileContent, writeFileContent } = require('../utils/readWriteFile');5const router = express.Router();6const FILE_PATH = './teams.json';7router.get('/', async (_req, res) => {8 const teams = (await readFileContent(FILE_PATH)) || { teams: [] };9 res.status(HTTP_STATUS_OK).json(teams);10});11router.post('/', isTeamValid, async (req, res) => {12 const { name, initials, country, league } = req.body;13 const newTeam = { name, initials, country, league };14 const teams = await readFileContent(FILE_PATH);15 if (!teams) {16 writeFileContent(FILE_PATH, { teams: [newTeam] });17 return res.status(HTTP_STATUS_OK).json(newTeam);18 }19 const newTeams = [...teams.teams, newTeam];20 writeFileContent(FILE_PATH, { teams: newTeams });21 res.status(HTTP_STATUS_OK).json(newTeam);22});...
bai2.js
Source:bai2.js
...6 return resolve(data.toString());7 });8 })9}10async function readFileContent(path){11 const result = await readFilePromise(path);12 console.log(result);13 return result;14}15readFileContent('./lyrics/7rings.txt').then(res => console.log(res));16module.exports = {17 readFileContent: readFileContent...
callbackhell2.js
Source:callbackhell2.js
1readFileContent("coba.md", function (a){2 readFileContent("coba2.md", function (b){3 readFileContent("coba3.md", function (b){4 writeFileContent("result.md", a + b + c, function(){5 console.log("we are done");6 })7 }) 8 })...
Using AI Code Generation
1import { readFileContent } from 'testcafe';2test('Check file content', async t => {3 const fileContent = await readFileContent('./test.txt');4 console.log(fileContent);5});6import { readFileSync } from 'fs';7test('Check file content', async t => {8 const fileContent = readFileSync('./test.txt');9 console.log(fileContent);10});11import { readFile } from 'fs';12test('Check file content', async t => {13 const fileContent = await new Promise((resolve, reject) => {14 readFile('./test.txt', (err, data) => {15 if (err) reject(err);16 else resolve(data);17 });18 });19 console.log(fileContent);20});21import fs from 'fs';22test('Check file content', async t => {23 const fileContent = fs.readFileSync('./test.txt');24 console.log(fileContent);25});26import fs from 'fs';27test('Check file content', async t => {
Using AI Code Generation
1import { TestcafeFileHelper } from 'testcafe-file-helper';2const fileHelper = new TestcafeFileHelper();3test('Test', async t => {4 const fileContent = await fileHelper.readFileContent('./test.txt');5 console.log(fileContent);6});
Using AI Code Generation
1import {TestcafeFileReader} from 'testcafe-file-reader';2test('Read File Content', async t => {3 const fileReader = new TestcafeFileReader();4 const fileContent = await fileReader.readFileContent('C:\\Users\\test\\Desktop\\test.txt');5 console.log(fileContent);6});7import {TestcafeFileReader} from 'testcafe-file-reader';8test('Read File Content', async t => {9 const fileReader = new TestcafeFileReader();10 const fileContent = await fileReader.readFileContent('C:\\Users\\test\\Desktop\\test.txt');11 console.log(fileContent);12});13import {TestcafeFileReader} from 'testcafe-file-reader';14test('Read File Content', async t => {15 const fileReader = new TestcafeFileReader();16 const fileContent = await fileReader.readFileContent('C:\\Users\\test\\Desktop\\test.txt');17 console.log(fileContent);18});19Hi, I am trying to read a file from a windows machine. I am able to read the file using the below code: import {TestcafeFileReader} from 'testcafe-file-reader'; fixture `TestCafe File Reader` .page `
Using AI Code Generation
1import { TestcafeFileReader } from 'testcafe-file-reader';2test('Check file content', async t => {3 const fileReader = new TestcafeFileReader();4 const content = await fileReader.readFileContent('path/to/file.txt');5 await t.expect(content).eql('file content');6});7import { TestcafeFileReader } from 'testcafe-file-reader';8test('Check file content', async t => {9 const fileReader = new TestcafeFileReader();10 const content = await fileReader.readFileContent('path/to/file.txt');11 await t.expect(content).eql('file content');12});13import { TestcafeFileReader } from 'testcafe-file-reader';14test('Check file content', async t => {15 const fileReader = new TestcafeFileReader();16 const content = await fileReader.readFileContent('path/to/file.txt');17 await t.expect(content).eql('file content');18});19import { TestcafeFileReader } from 'testcafe-file-reader';20test('Check file content', async t => {21 const fileReader = new TestcafeFileReader();22 const content = await fileReader.readFileContent('path/to/file.txt');23 await t.expect(content).eql('file content');24});25import { TestcafeFileReader } from 'testcafe-file-reader';26test('Check file content', async t => {27 const fileReader = new TestcafeFileReader();28 const content = await fileReader.readFileContent('path/to/file.txt');
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!