Guide to importing a JavaScript file into a different JavaScript file

I encountered an issue while trying to import a JavaScript file into my server-side JavaScript file. The function I need to run cannot be executed on the server side. Is there a method to successfully import my source code to the server-side JavaScript file so that the function can be executed? Your assistance is greatly appreciated.

JavaScript file for exporting to server-side

const {Builder, By, Key, util} = require("selenium-webdriver");

(async function googlesearch() {
    let driver = await new Builder().forBrowser('chrome').build();
    try{
        await driver.get("https://www.google.com/");
        let searchField = await driver.findElement(By.name('q'));
        await searchField.sendKeys("workout videos");
        await searchField.sendKeys(Key.ENTER);
        await driver.wait(until.titleIs('workout videos - Google Search'), 5000);

        let list = await driver.findElements(By.className('g'));
        if(list.length <= 0 ){
            throw new Error('Test - FAIL');
        }else{
            console.log('Test - Success');
        }
    } finally {
        console.log("automation complete")
    }
    
})();

Answer №1

One possible approach could be:

const {WebDriver, By, Key, until} = require("selenium-webdriver");

exports.runGoogleSearch = async () => {
  let driver = await new WebDriver.Builder().forBrowser('chrome').build();
    try{
        await driver.get("https://www.google.com/");
        let searchField = await driver.findElement(By.name('q'));
        await searchField.sendKeys("cat memes");
        await searchField.sendKeys(Key.ENTER);
        await driver.wait(until.titleIs('cat memes - Google Search'), 5000);

        let results = await driver.findElements(By.className('g'));
        if(results.length <= 0 ){
            throw new Error('Test - FAIL');
        }else{
            console.log('Test - Success');
        }
    } finally {
        console.log("Test completed successfully")
    }
}

Then you can import it like this:

const { runGoogleSearch } = require('./file/path')

Answer №2

Utilize the module.exports statement in the file you wish to import using Commonjs modules.

For instance

const {Builder, By, Key, util} = require("selenium-webdriver");

async function googlesearch() {
    let driver = await new Builder().forBrowser('chrome').build();
    try{
        await driver.get("https://www.google.com/");
        let searchField = await driver.findElement(By.name('q'));
        await searchField.sendKeys("workout videos");
        await searchField.sendKeys(Key.ENTER);
        await driver.wait(until.titleIs('workout videos - Google Search'), 5000);

        let list = await driver.findElements(By.className('g'));
        if(list.length <= 0 ){
            throw new Error('Test - FAIL');
        }else{
            console.log('Test - Success');
        }
    } finally {
        console.log("automation complete")
    }
    
});

// this was added here:
module.exports.googlesearch = googlesearch;

Then import/require it like this:

const {googlesearch} = require("./yourfilename");

or if you're using js modules export it like this:

export googlesearch;

And to import:

import {googlesearch} from "./yourfilename";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

What is the process for transferring a JSON data object to the server with JavaScript XMLHttpRequest?

When I attempt to send an XMLHttpRequest to a PHP server, I am encountering difficulties in getting the $_POST or $_REQUEST object to be filled with the data I am sending using JavaScript: var r = new XMLHttpRequest; r.open("POST", "http://url.com", true ...

Having issues with AngularJS ng-if when implemented within a Form

Is there a way to hide my form after it has been submitted using ng-if? I am facing an issue where clicking the 'See' button toggles the form on and off, but the same functionality does not work with the 'Add' button. Any insights on wh ...

Modal does not display the plothover tooltip

I am utilizing the flot Chart library to display a graph within a modal window. Everything is functioning properly except for the Tooltip popover not appearing when I hover over the plot. Below is my JavaScript code: $(document).on('click',&apos ...

A step-by-step guide on incorporating a dynamic data series into a line chart using the powerful tool

The data retrieved from a webservice is processed using the BindTrend method and then converted to a JSON object before being applied to the chart. The code for this process is as follows: var plot; var itemdata = []; var chart; var data = [] ...

Check an array of objects for duplicate key-value pairs by cross-referencing other key-value pairs within the array using JavaScript

let selectedFruit = "mango" let fruitArray = [{fruit:"apple",locale:"US"}, {fruit:"orange",locale:"US"}, {fruit:"banana",locale:"US"}, {fruit:"apple",locale:"US"}, {fruit:"orange",locale:"IT"}, {fruit:"apple",locale: ...

Step-by-step guide on sending JSON data to a server using AJAX and jQuery

Encountering Error While Trying to Send 'Order' JSON Data to JSON File on Node.js Server Everything seems fine with the GET request, but when attempting a POST request, the 'Error' function is triggered instead of the 'success&apo ...

Understanding the scope within a jQuery each method

It's puzzling to me why the scope of $elm seems to be lost within the jQuery each loop. The scope is reliable on lines 76 and 77, but then disappears inside the loop at line 78. What mistake am I making? Take a look at this image displaying the code. ...

Attempting to make a selection from a drop-down menu

The following code was attempted, but it does not seem to be functioning correctly. driver.get("http://www.naukri.com/"); WebElement element = driver.findElement(By.xpath("//input[@placeholder='Salary']")); Select s1 = new Select(element); s1.se ...

Access account without providing all necessary identification documents

I'm currently facing an issue with my User Schema, as I initially defined 3 inputs for name, surname, and email. However, I now want to allow users to log in only with their email and password, without having to input their name and surname. How can I ...

Which JavaScript framework tackles the challenges of managing asynchronous flow, callbacks, and closures?

I have a strong aversion to JavaScript. I find it to be quite messy and disorganized as a language. However, I recognize that my lack of proficiency in coding with it may contribute to this perception. These past few days have been incredibly frustrating ...

"Discover the art of arranging div elements into a grid format with multiple rows and two columns

<div class="parent"> <div class="col">1</div> <div class="col">2</div> <div class="col">3</div> <div class="col">4</div> <div class="col">5</div> <div class="col">6</div ...

Are you experiencing empty boxes instead of Glyphicons in Bootstrap 3?

Having some trouble using Glyphicons with Bootstrap 3. I've noticed that a few of them aren't displaying properly. For instance, when trying to use these three glyphicons, the first one doesn't seem to show up correctly (appears as an empty ...

Issue encountered while attempting to run executeJavascript()

Hello, I’m looking to insert the output of a Python function that I have stored in the variable data. However, when I attempt to insert the value of this variable using the command document.getElementById("h1-fs-s5").innerHTML, it doesn’t work as expec ...

Is your Scrollmagic failing to function once your website is uploaded to the server?

My website incorporates Scrollmagic to dynamically load sections (changing opacity and adding movement) as users scroll through it. Everything functions perfectly fine when I preview the HTML file on my computer, but once I uploaded it to my hosting serv ...

The backtick is not functioning correctly when trying to append the result in the Internet Explorer browser

I am using the .html method to append HTML content to a specific div ID within my file. <html> <head> Title <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> ...

The React application is experiencing difficulty in rendering SVG images exclusively on Windows operating systems

My react app runs smoothly on OSX, but encounters issues on Windows due to SVG files: Module parse failed: Unexpected token (2:0) You may need an appropriate loader to handle this file type. <svg xmlns="http://www.w3.org/2000/svg" viewBox="..."> I ...

Utilizing negative values in lineTo, strokeRect, and fillRect functions

Is it possible to input negative numbers into the drawing primitives of HTML5 canvas? For instance, if I apply a translation of (100,100), would I be able to draw a rectangle or line with coordinates (-25,-25)? Initial testing using lineTo seems inconclus ...

Encountering difficulty in retrieving data from an unidentified JSON array using Javascript

Exploring the realm of Javascript and JSON, I find myself faced with a challenge - accessing values in an unnamed JSON array. Unfortunately, as this is not my JSON file, renaming the array is out of the question. Here's a snippet of the JSON Code: [ ...

My initial junior UI/UX assignment: Can you confirm whether this form modal dialog is pixel-perfect, and offer any suggestions for improvements

Currently diving into my first project as a Junior UX/UI Designer. Coming from a background in software engineering, I decided to challenge myself by focusing on design. I'm seeking feedback on the pixel perfection of this modal window, which my seni ...