Identifying a problem in my code and having other errors acknowledged

The command window is displaying the following:
C:\Users\Dell\Desktop\PROGRA~1>node revers~2.js
events.js:160

  throw er; // Unhandled 'error' event
  ^

Error: ENOENT: no such file or directory, open  
'C:\Users\Dell\Desktop\PROGRA~1\Input_File.txt'
at Error (native)

I am unsure what this error is referencing, but I suspect it might be related to the Node.js software used for running my code.

Any assistance you can offer is greatly appreciated. I apologize if this question seems basic or self-explanatory, as I am unable to pinpoint the issue.

It is possible that my code may not be suitable for the task at hand.

The Input_File.txt contains:

15 12 2 + -4 * + 3 - 

This data in the file pertains to a Reverse Polish Function that I am trying to implement and solve through the program.

'use strict' ;

var ArrayStack = require('./ArrayStack');
const fs = require('fs');
const readline = require('readline');

var ArrayStack2 = new ArrayStack();
var readStream = fs.createReadStream('Input_File.txt', 'utf8');
var rl = readline.createInterface({input: readStream});
rl.on('line', function(inputLine) {
    console.log(inputLine);
    var tokens = inputline.split(' ');
    for (var i = 0; i < tokens.length; i++) {
        const token = tokens[i];
        var tokenCategory = 'operand';
        if (token === '+' || token === '-' || token === '/' || token === '*') {
            tokenCategory = 'operator';
            var B = ArrayStack2.pop();
            var A = ArrayStack2.pop();
            if (token === '+') {
                var answer = A + B;
                ArrayStack2.push(answer);
            } elseif (token === '-') {
                var answer = A - B;
                ArrayStack2.push(answer);
            } elseif (token === '/') {
                var answer = A / B;
                ArrayStack2.push(answer);
            } elseif (token === '*') {
                var answer = A * B;
                ArrayStack2.push(answer);
            }
        } else {
            ArrayStack2.push(token);
            console.log(ArrayStack);
        }
    }
});

rl.on('close', function() {
    console.log('File now closed.');
}); 

In order to store and solve the problem, an ArrayStack class is utilized.

'use strict' ;

var EmptyError = require('./EmptyError');

class ArrayStack {
    constructor() {
        this._data = new Array();
    }

    isEmpty() {
        return (this._data.length === 0);
    }

    push(toPush) {
        this._data.push(toPush);
        return this;
    }

    pop() {
        if (this.isEmpty())
            throw new EmptyError("Can't pop from an empty stack!");
        return this._data.pop();
    }

    top() {
        if (this.isEmpty())
            throw new EmptyError('An empty stack has no top!');
        return this._data[this._data.length - 1];
    }

    len() {
        return this._data.length;
    }
}

module.exports = ArrayStack;

The EmptyError class is referenced in relation to the ArrayStack class.

'use strict';

class EmptyError extends Error {
    constructor(message) {
        super(message);
    }
}

module.exports = EmptyError;

Answer №1

'operator' !== '-' is a string comparison. It's important to note that operator cannot be equated to symbols like -,/,*.

While it has not been verified, it seems like the comparison should be made with the token variable rather than the operator itself.

if (token === '+' || token === '-' || token === '/' || token === '*') {
  // Rest of code
  if (token === '+') {
} else if (token === '-') {
    // more code here
  }
// additional code
}

Answer №2

The issue with the else being flagged as an "unexpected token" arises from incorrect usage of { and } in the if/else if/else structure.

The accurate syntax should be:

if (condition) {
  statement1
} else if (condition) {
  statement2
} else {
  statement3
}

...where the curly braces { and } are optional for a single statement but mandatory for multiple ones within a block.

In your code, each if and else if block spans two lines, necessitating encapsulation within { and }.

Furthermore, the semicolon at the end of this line:

if ( token === '+' || token === '-' || token === '/' || token === '*' ) ;

signifies no execution if the if condition is met, despite commencing the next line with a {.

To rectify bracket misplacements, your revised segment should resemble:

function(inputLine) {
  console.log(inputLine);
  var tokens = inputline.split(' ');
  for (var i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    var tokenCategory = 'operand';
    
    if (token === '+' || token === '-' || token === '/' || token === '*') {
      tokenCategory = 'operator';
      
      var B = ArrayStack.pop();
      var A = ArrayStack.pop();
      
      if (token === '+') {
        var answer = A + B;
        ArrayStack.push(answer);

      } else if (token === '-') {
        var answer = A - B;
        ArrayStack.push(answer);

      } else if (token === '/') {
        var answer = A / B;
        ArrayStack.push(answer);

      } else if (token === '*') {
        var answer = A * B;
        ArrayStack.push(answer);
      }
    } else {
      ArrayStack.push(token);
      console.log(ArrayStack);
    }
  }
}

(You can also place the curly brackets on separate lines per preference.)

Moreover, ensure you're comparing variable token rather than the string 'operator' where needed.

Answer №3

Don't forget to include basic if-else brackets in your code. As mentioned by @brk, make sure you are comparing two strings: 'operator' and '+', '-'. Below is the revised code for you to review.

'use strict';

var ArrayStack = require('./ArrayStack');
const fs = require('fs');
const readline = require('readline');

new ArrayStack();
var readStream = fs.createReadStream('Input_File.txt', 'utf8');
var rl = readline.createInterface({input: readStream});
rl.on('line', function(inputLine) {
    console.log(inputLine);
    var tokens = inputLine.split(' ');
    
    for(var i = 0; i < tokens.length; i++) {
        const token = tokens[i];
        var tokenCategory = 'operand';
        
        if(token === '+' || token === '-' || token === '/' || token === '*') {
            tokenCategory = 'operator';
            var B = ArrayStack.pop();
            var A = ArrayStack.pop();
            
            if(token === '+') {
                var answer = A + B;
                ArrayStack.push(answer);
            }
            elseif(token === '-') {
                var answer = A - B;
                ArrayStack.push(answer);
            }
            elseif(token === '/') {
                var answer = A / B ;
                ArrayStack.push(answer);
            }
            elseif(token === '*') {
                var answer = A * B;
                ArrayStack.push(answer);
            }//end of sub conditional statement
        } 
        else {
            ArrayStack.push(token);
            console.log(ArrayStack);
        }
    }//end of for loop
}); //end of function  

rl.on('close', function() {
    console.log('File now closed.');
}); // end function

I have made some changes to your code based on my understanding. Make sure to test this updated version.

var ArrayStack = require('./ArrayStack');
const fs = require('fs');
const readline = require('readline');

var myStack;
var readStream = fs.createReadStream('Input_File.txt', 'utf8');
var rl = readline.createInterface({input: readStream});
rl.on('line', function(inputLine) {
    console.log(inputLine);
    var tokens = inputLine.split(' ');

    ArrayStack.init(tokens, function(err, data) {
        if (err) {
            console.error('Error received');
        } else {
            myStack = data;
            console.log('pushed data ' + data.first());
        }
    });

    for (var i = 0; i < tokens.length; i++) {
        const token = tokens[i];
        var tokenCategory = 'operand';

        if (token === '+' || token === '-' || token === '/' || token === '*') {
            tokenCategory = 'operator';
            var B = myStack.pop();
            var A = myStack.pop();

            if (token === '+') {
                var answer = A + B;
                myStack.push(answer);
            } elseif (token === '-') {
                var answer = A - B;
                myStack.push(answer);
            } elseif (token === '/') {
                var answer = A / B;
                myStack.push(answer);
            } elseif (token === '*') {
                var answer = A * B;
                myStack.push(answer);
            } //end of sub conditional statement
        } else {
            myStack.push(token);
            console.log(myStack);
        }
    }//end of for loop
}); //end of function

rl.on('close', function() {
    console.log('File now closed.');
}); // end function

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

What steps should I take to ensure that the content within a div also goes full screen when I expand the div?

Is there a way to make a flash game go full screen along with its container div? I have a button that expands the div to full screen, but the flash game inside remains stuck in the top left corner of the screen. How can I ensure that the flash game expands ...

Retrieve the content of the 'div' element, but exclude certain text

I have a task to copy the content from a div into a textarea, allow for editing within the textarea, and ensure that any changes made are saved back to the original div. I also need to filter out an attribute, such as data-bind: "some stuff;", set for the ...

When submitting a form in HTML, ensure that the input checkbox returns 'On' instead of 'True'

My MVC3 app is using Project Awesome from http://awesome.codeplex.com/, but I'm encountering a strange issue with checkboxes. Inside a Modal popup, I have the following simple Html code: <input type="checkbox" class="check-box" name="IsDeleted"> ...

Changing Text Color in Adobe Acrobat using Javascript

After creating an editable PDF using Adobe Indesign, I encountered an issue with font color when editing the text in Adobe Acrobat. The default font color was black, but I wanted it to be white. Despite my limited knowledge of Javascript, I managed to find ...

What causes the "Invalid hook call" error to occur when the useQuery function is invoked?

Encountering an issue while trying to use the useQuery() function from react-admin within a custom component. Despite the clear error message, I'm struggling to determine the right course of action. Visiting the provided website and following the inst ...

Adding a JavaScript file to enhance the functionality of an AJAX response

In my project, I have implemented a dropdown that triggers an AJAX call each time an option is selected. The AJAX call returns HTML markup containing buttons, text boxes, and a script tag. The buttons in the HTML markup use this script tag to submit data t ...

Displaying the most recent queries retrieved from a search API

Our web application built on angular.js utilizes a REST search API to query users within the system. The endpoint for searching users is: search/user?q='abc' Upon revisiting the web application, we aim to display the user's recent search ...

Creating a form element in JavaScript and submitting it - step by step tutorial

Is there a way to redirect to a different page once a JavaScript process running on the current page is finished? The issue here is that only JavaScript knows when it's complete, and I'm using Python (Flask) as my web framework. One solution I th ...

What is the best way to create a fixed navigation bar that only stays fixed on particular sections of my website?

In my digital portfolio, I have divided it into "4 sections," each represented by a separate scrollable web page. These sections are also known as parts, starting from #part1 up to 4. For section 1 (#part1), I prefer not to display the navigation bar. How ...

The most recent version of Autonumeric now permits the inclusion of a decimal point, even if the decimalPlaces parameter

I need to ensure that only whole numbers are allowed in the input textboxes, while also displaying a currency symbol and commas. I am using the most recent version of Autonumeric JS for this purpose. Even after setting the decimalPlaces property to 0, I a ...

Scrolling to a specific element using jQuery after a specified delay has

On my website, I have a page with an autoplaying video located at . My goal is to implement a feature where once the video completes playing after a specific duration, the webpage will automatically scroll down to the text section. This scroll action sho ...

I am attempting to display films within a watchlist module, however it is not allowing me to do so

I have developed a small movie database and need to showcase movies on my watchlist. While I am able to search for movies, adding them to my watchlist is only reflected in the Homescreen component and not in the WatchList component. This is the current s ...

Minimization tools for compressing CSS and JavaScript documents

After deploying my application, I noticed that the loading time has significantly increased. Is there a way to compress CSS and JS files? I include only the necessary code in each page and occasionally use minified versions of JS. Thank you. ...

What is the best way to incorporate alternating classes into a dynamic feed of thumbnail images?

I am integrating a YouTube user's video channel feed onto a webpage using two plugins called jYoutube and jGFeed. If you are interested in the plugins I mentioned, here they are: jGFeed: jYoutube: However, I have encountered an issue with the im ...

JavaScript and HTML have encountered an Uncaught TypeError: The property 'addEventListener' cannot be read because it is null

Having an issue here. Whenever I try to play sound from an image, I encounter an error. Uncaught TypeError: Cannot read property 'addEventListener' of null Here is my HTML code: <html> <head> <title>Music</title> < ...

Steps for installing an npm package from a downloaded folder

In the past, I had a method of installing an npm project from Github that involved using git clone followed by npm install. git clone http...my_project npm install my_project Instead of manually copying the contents of my_project to my local node_modules ...

Multiple Button Triggered jQuery Ajax Function

I'm currently working on a project where I retrieve data from MySQL to create 4 buttons. I am using jQuery/ajax to trigger an event when any of the buttons are clicked. However, only the first button seems to be functioning properly, while the other t ...

Ways to extract repeated value from a function?

Currently, I am working with two files. One file contains a script that generates a token, while the other file handles that token. The issue arises with the second script, as it only logs the initial token received and does not update with any new values ...

Tips for transferring the name field to a different page upon clicking

There are two pages in my project - the first one is called ItemMenuPage and the second one is called CartPage. The functionality I am trying to achieve is that when a user clicks on any item name on the ItemMenuPage, it should navigate to the CartPage, wi ...

Searching for a jQuery plugin that can dynamically rearrange tables while automatically updating their corresponding IDs

Is there a way in jQuery to dynamically move tables around on a webpage? Currently, I have implemented a button that clones a hidden table when needed and another button to delete unwanted tables. Now, I am looking to incorporate a feature that allows the ...