Is there a way to execute a JavaScript file within another JavaScript file?

I'm in the process of developing a text-based game through the console, utilizing an NPM package known as "prompts" to prompt the user for input. One specific question it asks is, "What OS do you want to run?" and returns the selection as JSON data. For instance, if the user chooses "OS 1", the response would be { Bootup: "StartOS1" }. My goal is to execute different JavaScript files based on this selection using an if statement:


if(Bootup == "StartOS1") {
 // Insert code to execute another JS file here.
}

However, I'm uncertain what to include within this section.

Initially, I attempted to achieve this task with the help of a separate NPM package titled shelljs, which allows for shell execution:


const shell = require('shelljs')

if(Bootup == "StartOS1") {
  shell.exec('node OS1.js')
}

Unfortunately, this approach resulted in my shell becoming unresponsive and stuck at a blank line indefinitely, requiring a system restart. This situation highlights the essence of what I'm striving to accomplish.

Answer №1

shell.exec('node OS1.js') is a synchronous function that can cause your program to become blocked. If your JavaScript file is waiting for an event, it may prevent your functions from running properly. A better alternative is to use the exec() method from the child_process module:

const { exec } = require('child_process');

exec('node OS1.js', (error, stdout, stderr) => {
    if (error) {
        console.error(`exec error: ${error}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
    console.error(`stderr: ${stderr}`);
});

While there are other methods available, this approach involves reading the JavaScript file as a string and then executing it using the synchronous eval function. However, it's worth noting that using eval is not considered best practice due to security concerns.

const fs = require('fs');
fs.readFile('./node OS1.js', 'utf8', function(err, data) {
    if (err) {
        console.error(err);
        return;
    }
    eval(data);
});

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

Obtaining data objects with Angular 2 from JSON

Recently, I received a URL that includes data arrays in JSON format. My goal is to retrieve and utilize all elements within it: However, when attempting this, I end up with everything but nothing specific. For instance: How can I access data.name or data. ...

Error: Module not found '!raw-loader!@types/lodash/common/array.d.ts' or its type declarations are missing

I encountered a typescript error while building my NEXT JS application. The error message was: Type error: Cannot find module '!raw-loader!@types/lodash/common/array.d.ts' Below is the content of my tsConfig.json file: { "compilerOptions& ...

How come eslint is unable to detect all files within a directory, yet it can detect a single file?

Here is the organization of my files and directories. https://i.stack.imgur.com/YWNw3.png I am looking to set up some eslint rules for my code detection. In my .eslintrc file, I have included these configuration settings. { "extends": "airbnb", "ru ...

The asynchronous ajax request is leading to a browser freeze

In the HTML page, I have two sets of a and p elements that are initially set to display:none. At the bottom of the page, there is a function being called with their respective ID's and values, which will enable one of them based on certain conditions ...

"Graphs not Displaying Properly in ChartJs

Seeking assistance with rendering a chart inside a bootstrap popover. Despite various debugging attempts, the chart refuses to render. Any help or insight would be greatly appreciated. Below is my HTML code: <div id="popover-content" style=&qu ...

Node.js: Extracting parameters from the URL

When working with Rails, I make a POST request to my server: response = Typhoeus::Request.post("http://url.localtunnel.com/request?from=ola&to=ole") result = JSON.parse(response.body) Now in my Node.js application, I need to retrieve values for From ...

Line numbers in Vue Codemirror

Currently, I'm working on integrating codemirror into my Vue.js application using a library found at https://github.com/surmon-china/vue-codemirror. The issue I'm facing is that even after importing and utilizing the codemirro component, everythi ...

Issues arise when using the bootstrap-editable library alongside the Karma Test Runner due to conflicts with undefined objects

Despite searching extensively, I have not been able to find a solution to my specific issue among the many threads on this topic. Most of the solutions mentioned seem to pertain to Angular or other unrelated problems. My ReactJS project is using node v6.5 ...

Prevent Click Event in JQuery

I have a requirement to disable all click events on my webpage. However, even after using the appropriate code to prevent these events from firing, some of them are still getting called. Let me explain with an example. <div id='parent'> ...

The jQuery $.change function is not functioning properly when used with a cloned select element

In my table, there is a button that allows you to add a new row by cloning the last one. Each row contains a <select> with a different name (0-9), all having the class .variable_priority. When clicking the button, the row clones successfully and the ...

The propagation of SVG events from embedded images via the <image> elements

I'm currently developing a diagramming tool using HTML, CSS, and Javascript with SVG for the drawing canvas. This tool consists of predefined "building blocks" that users can place on the canvas, rather than allowing free-hand drawing of shapes. Each ...

Unable to retrieve information from JSON file utilizing AngularJS version 1.6

I'm having trouble retrieving data from my JSON file using AngularJs 1.6 myApp.controller("homeCtrl", function($scope, $http) { $scope.Data = []; var getJsonData = function() { $http.get('contactlist.json').then(func ...

An error message stating "ReferenceError: str is not defined" was encountered in Firefox while using the Gettext Library

The gettext.js library seems to be giving me trouble. When I try to run the "index.html" file, an error message saying "ReferenceError: str is not defined" pops up. this.LCmessages[lang] = new jsGettext.Parse(str); I'm not sure where the str variabl ...

Verifying the activation status of a button within a Chrome extension

I have been working on a chrome plugin that continuously checks the status of a button to see if it is enabled. If it is, the plugin clicks on the button. I initially used an infinite for loop for this task, but realized that it was causing the browser to ...

terminate the express middleware and return a custom HTTP status code

Is it possible to use custom middleware to return a 404 or 401 error to the user and prevent other handlers from running? I tried implementing the following code: function SomeMiddleware(req, res, next) { if(user.notRealOrSomething) { throw new Htt ...

Vue component input form not providing expected result

Here is the code snippet for my "ecedata" component with an input field: <template> <div class="col-l-4"> <p style="text-align: center">Data/day (GB)</p> <div class="form-input-set" style="background: white"& ...

Need help resolving the issue of "Type Property '' does not exist on type 'IntrinsicAttributes & Function'? Let's find a solution together

Looking at my parent component below: import FilterComponent from 'filter/filterComponent' const handleReload = useCallback( (event: MouseEvent) => { event.preventDefault(); // implement logic here }, [Reload, Fetch ...

The calendar loses its focus when I try to interact with it

One issue I have encountered is that when I click on the input field to display the Calendar component, and then click outside of it to hide it, everything works smoothly. However, the problem arises when I click directly on the icon (Calendar component) i ...

What causes a delay in the start of a child process in Node.js?

I am in the process of developing a global node command line program that can execute any console command I provide it with in a new console window, whether on a Windows or Unix system. The goal is for the program to exit after it spawns its process so tha ...

Utilizing JavaScript and JSON to Retrieve Array Elements by Key Names as Indexes

I'm looking for a way to access elements in an array using unique key names instead of numerical indexes. Specifically, I'm developing a Discord bot where each server has its own settings. When a message is sent on a server, I need to retrieve th ...