Encountering an error while using JSON.parse

I have just finished writing this code snippet:

function getScreenshotObj (pathToFirstFile) {
    return new Promise ((resolve,reject) =>{
        console.log("The path to the temporary directory is: " + pathToFirstFile)
        fs.readFile(pathToFirstFile,function(err,fileContents){
            if (err) {
                return reject(err)
            }
            else{
                screenshotObject = JSON.parse(fileContents)
                obj = {pathToFirstFile : pathToFirstFile , screenshotObject:screenshotObject ,accesstoken : accesstoken}
                return resolve(obj)
            }
        })
    })
}

I am encountering an error at JSON.parse(). Specifically, it is giving me an 'Uncaught syntax error: Unexpected end of input' at that line. I have verified the syntax using online JS validators, and they indicate that the code is syntactically correct. Could someone please review my code and point out any mistakes I may have made?

Answer №1

When using fs.readFile, if you do not specify encoding, it will return raw data buffer. source

Replace:

fs.readFile(pathToFirstFile, function(err, fileContents) {

with:

fs.readFile(pathToFirstFile, 'utf8', function(err, fileContents) {

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

Static express is failing to load the node_modules folder

Why am I facing difficulties with my website not being able to use the node_modules directory on my server? const express = require('express'); const app = express(); app.use(express.static(__dirname + '/public')); app.listen(8080, &ap ...

Control the frequency of server requests within a set limit

Currently, I am utilizing the request-sync library to fetch data from a specific site's API. This is how my code looks: let req = request('GET', LINK, { 'headers': { 'Accept' ...

Modifying the names of certain keys within a JSONArray

After receiving a JSONArray response from an HTTP request, I noticed that some of the keys in the JSON response have names like Total_x200_Price or Creation_x200_Date, where spaces are represented by "x200" instead of actual spaces. This is causing issues ...

Is it possible to implement JSON in place of SQLite for my Android application?

Currently, I am working on a basic android application that includes an activity dedicated to showcasing data extracted from a few tables in an online mySQL database. These tables are fairly straightforward and will not exceed 100 rows. In order for the a ...

"Enhance Your Website with Customized Background Sound Effects

Currently, I have been developing an application. Now, I am in the stage where I need to incorporate some background music into it. I am planning to utilize jQuery for playing the music and looping it once it finishes. Here is the specific background tr ...

Display the results of the constantly changing JSON response

I am expecting to receive a dynamic JSON response based on the provided input. Here is an example: { results: [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c487c6d7b7c266b6765">[email protec ...

Execute a function precisely at the start of every second (or at a designated millisecond interval each second)

My goal is to execute a function at the start of every second. Here's an example: function loop() { console.log('loop', new Date()); } setInterval(loop, 1000); Upon running this script with node v11.13.0, I observed the following out ...

Preventing an image from being repeated when using Canvas drawImage() without having to clear the entire canvas

How can I prevent multiple instances of the same image from smearing across the canvas when drawing it? The platforms seem to stick together and not separate properly. Why do I have to clear the entire rectangle for everything to disappear? Does anyone ha ...

Managed the double-click event to select Snap.svg text

I am currently utilizing the snapsvg library for a project where I am implementing the dblclick event to trigger a browser window alert. However, when clicking on the svg canvas, not only does the alert pop up but some text on the canvas also gets selected ...

Changing JSON array into an array of Objects - Apache Camel

[ { "Name": "ABC", "ID": 1, "StartDate": 1444845395112, "EndDate": null, "ValueAction": null, "ValueSource": "lmn" }, { "Name": &q ...

The $.ajax POST method successfully sends data to the server, but the $.ajax PUT method fails to do so

When utilizing jQuery to make an ajax call, I observed that using the POST method works perfectly fine. However, when switching to the PUT method without any other alterations, the object data is not being sent. This has led me to the question of why this ...

How to generate nested arrays in JSON format using MySQL data

My goal is to generate JSON using PHP from data in two MySQL tables: - Categories (unique) - Subcategories or Rights (multiple within the same category) However, I'm struggling to display multiple subcategories under one category. Currently, a ne ...

Express server failing to deliver static assets

I am currently developing an app using Express and socket.io, but I am facing an issue where my server is unable to locate the static files. Despite searching for solutions online and trying various methods such as referencing the public folder with expres ...

Having trouble with Vue component registration repeatedly failing

Currently, I am working on a front-end project using [THIS VUE TEMPLATE][https://www.creative-tim.com/product/vue-material-dashboard-pro] The issue I am facing involves trying to register a component locally and encountering the following error: "1 ...

Ways to extract pertinent information from a PHP API

I've been attempting to add parameters to my query, but I keep getting inconsistent results. Despite trying different methods, I haven't been successful. Take a look at the code below. First, here is my code that functions properly without using ...

Differences between Mongoose's updateOne and save functions

When it comes to updating document records in a MongoDB database, there are several approaches to consider. One method involves defining the User model and then locating the specific user before making modifications and saving using the save() method: let ...

How to retrieve information from an Ajax POST call using PHP?

Struggling to successfully send a POST request using Ajax and facing issues retrieving the values in PHP. Take a look at my JavaScript code below: $.ajax({ url: "updatedata.php", type: 'post', data: JSON.stringify(jsonData), cont ...

Efficiently Extracting Information from JSON Objects

Currently, I am in the process of parsing a JSON file. Let's assume that the JSON data looks like this: {"data" : [ {"ID":12, country: "UK"}, {"ID":13, country: "USA"}, {"ID":14, country: "BRA"}, ]} Instead of just having three entries as show ...

Having trouble loading CSS file in node js after submitting form

Before diving into more details, let me explain my current situation. I am utilizing node's nodemailer to facilitate the process of sending emails based on the information submitted through a form. Initially, everything was functioning smoothly when t ...

Retrieve name and value pairs from a JSON string stored in a MySQL database and insert them into another

In my MySQL database, I have a column called 'other' in 'table_one', which stores JSON strings. This table contains millions of records. A. My goal is to loop through 'table_one', extract data from the 'other' co ...