-1

This question is not the same as: Load local JSON file into variable

I've just tried implementing that change and nothing...

I've been finding that When I run my json string results through my web browser I'm getting

Uncaught ReferenceError: require is not defined

I'm using Node.js as my platform for running this.

After looking into this I'm still no further forward. I don't want to use Browserfy or webpack. And I'm not using Jquery.

This works when I hard code my two json strings into index.js. However I'm need it to be variable.

I need a pure JavaScript way of reading the .json file without using require. As I've seen

let fs = require('fs');

which will enable me to read the file however that's a require...

I have my HTML and Index.js files below if you can suggest anything.

Webpage.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test Out Put to HTML Page</title>
    </style>
</head>
<body>
<div id ='TestResults'>
    <div id = 'TestOutput'>Nothing Yet</div>
</div>
<div id ='ErrorResults'>
    <div id = 'ErrorOutPut'>Nothing Yet</div>
</div>
<script type = 'text/javascript' src = 'index.js'></script>
</body>
</html>

Index.js

let myJsonString = require('../../ResultsArray/ResultsArray');
let myJsonStringError = require('../../ResultsArray/ErrorArray');

function result(results){
    if(results === 'YesNo')
    {
        return 'Passed'
    }
    if(results === 'NoYes')
    {
        return 'Failed'
    }
    else
    {
        return 'Unknown'
    }
}

function time (value){
    // 1- Convert to seconds:
    let seconds = (value / 1000).toFixed(2);
    // 2- Extract hours:
    let hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
    seconds = seconds % 3600; // seconds remaining after extracting hours
    // 3- Extract minutes:
    let minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
    // 4- Keep only seconds not extracted to minutes:
    seconds = (seconds % 60).toFixed(2);
    return ([hours+":"+minutes+":"+seconds]);
}

function testTemplateErrors (test){
    return `
    <tr>
    <td class='TestGroup'>${test.Folder}</td>
    <td class='TestName'>${test.Test_Name}</td>
    <td class='TestsStatus'>${test.Running}</td>
    <td class='TestRunTime'>${time(test.Run_Time)}</td>
    <td class= 'TestResult'>${result(test.Passed + test.Failed)}</td>
    </tr>
    `
}

function testTemplateResults (test){
    return `
    <tr>
    <td class='TestGroup'>${test.Folder}</td>
    <td class='TestName'>${test.Test_Name}</td>
    <td class='TestsStatus'>${test.Running}</td>
    <td class='TestRunTime'>${time(test.Run_Time)}</td>
    <td class= 'TestResult'>${result(test.Passed + test.Failed)}</td>
    </tr>
    `
}

if(myJsonString && myJsonString.length)
{
    document.getElementById('TestResults').innerHTML = `
    <h1 class='ContentTitle'> Regression Tests (${myJsonString.length} Tests Ran)</h1>
    <table><tr>
    <th>Result Folder Name</th>
    <th>Result Test Name</th>
    <th>Result Running</th>
    <th>Result Run Time</th>
    <th>Result Result</th>
    </tr><tr>
    ${myJsonString.map(testTemplateResults).join('')}
    </tr></table>
    <p class='footer'> These ${myJsonString.length} Results were added recently. </p>
    `
}

if(myJsonStringError && myJsonStringError.length)
{
    document.getElementById('ErrorResults').innerHTML = `
    <h1 class='ContentTitle'> Error Results (${myJsonStringError.length} Errors Occurred)</h1>
    <table><tr>
    <th>Error Folder Name</th>
    <th>Error Test Name</th>
    <th>Error Running</th>
    <th>Error Run Time</th>
    <th>Error Result</th>
    </tr><tr>
    ${myJsonStringError.map(testTemplateErrors).join('')}
    </tr></table>
    <p class='footer'> These ${myJsonStringError.length} Results were added recently. </p>
    `
}
Daniel
  • 45
  • 6
  • Possible duplicate of [Load local JSON file into variable](https://stackoverflow.com/questions/14484613/load-local-json-file-into-variable) – Weedoze Aug 08 '18 at 09:02

2 Answers2

0

require is provided by Node.js, not by browsers, and also by bundlers like Webpack or Browserify. If you're running browser-based code and not using one of those tools or RequireJS, it will not exist in the browser environment.

To read a resource from browser-based code, you'd use ajax. The modern way to do that is to use fetch (previously, you'd use XMLHttpRequest). Here's a simple fetch example for something returning JSON:

fetch("/url/to/the/resource")
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error: " + response.status);
    }
    return response.json();
})
.then(data => {
    // ...use the data here, it's been parsed...
})
.catch(error => {
    // Something went wrong, handle/report it
});

As I note on my anemic blog, it's very easy to forget that .ok check and tedious to re-code it all the time, so I use a helper:

const myFetch = (...args) => fetch(...args).then(response => {
    if (!response.ok) {
        throw new Error("HTTP error: " + response.status);
    }
});

...which you'd use like this to fetch JSON:

myFetch("/url/to/the/resource")
.then(response => response.json())
.then(data => {
    // ...use the data here, it's been parsed...
})
.catch(error => {
    // Something went wrong, handle/report it
});

If you want to fetch multiple resources and wait for them all to arrive, use Promise.all:

Promise.all([
    myFetch("../../ResultsArray/ResultsArray.json").then(response => response.json()),
    myFetch("../../ResultsArray/ErrorArray.json").then(response => response.json())
])
.then(([resultsArray, errorArray]) => {
    // ...use `resultsArray` and `errorArray` here...
})
.catch(error => {
    // Handle/report error
});

All of those examples assume ES2015-ES2017. If you can use ES2018 features, taht code can be more synchronous-looking using an async function.

Note that fetch (like XMLHttpRequest) is asynchronous; these questions may help with issues you may have as a result of that:

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • When I've altered my index.js file to show your changes I get back "Failed to load resource: the server responded with a status of 404 (Not Found)". even though they are in the location specified. – Daniel Aug 08 '18 at 09:19
  • @Daniel - If you're getting a 404, the URL is wrong. My guess is you're missing out a file extension (`.json` or `.js`), since they weren't on your `require` calls (Node.js infers `.js` if you leave it off; browsers don't). – T.J. Crowder Aug 08 '18 at 09:29
  • Ok I tried this: `fetch("../../ResultsArray/ErrorArray.json") .then(response => { if (!response.ok) { throw new Error("HTTP error: " + response.status); } return response.json(); }) .then(data => { myJsonString = data; }) .catch(error => { console.log('Error.json could not be found'); });` And I get the .jsons in the Network tab when I inspect the html page however Its not linking to my json string within the index.js file. – Daniel Aug 08 '18 at 09:31
  • @Daniel - I don't know what you mean by *"...Its not linking to my json string within the index.js file..."* The data from the JSON files is accessible where I showed above (and not globally). See the linked questions at the end of the answer for more details on that, as indicated. – T.J. Crowder Aug 08 '18 at 09:39
  • I've added in another explanation as to what I mean. – Daniel Aug 08 '18 at 10:10
  • @Daniel - If you mean the answer you posted, that's usually not best practice, because the variables will have the value `undefined` until / unless the fetches complete. Again, see the questions linked at the end of the answer above. But yes, you *can* do what you do in that answer; that's just one of many ways you might "use" the results as indicated in my answer. – T.J. Crowder Aug 08 '18 at 10:13
  • Could I wrap that in a promise and resolve upon data being brought back? – Daniel Aug 08 '18 at 10:43
-1

I tried to set the response from the fetch to a variable:

let myJsonString;
let myJsonStringError;

fetch("../../ResultsArray/ResultsArray.json")
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error: " + response.status);
        }
        return response.json();
    })
    .then(data => {
        myJsonString = data;
        console.log(myJsonString);
    })
    .catch(error => {
        console.log('Results.json could not be found');
    });

fetch("../../ResultsArray/ErrorArray.json")
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error: " + response.status);
        }
        return response.json();
    })
    .then(data => {
        myJsonStringError = data;
        console.log(myJsonStringError);
    })
    .catch(error => {
        console.log('Error.json could not be found');
    });

And I can see the .Json files in my network tab. Network Tab results

Daniel
  • 45
  • 6