Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
[Node.js]Access json file in another folder with file.readFile

Im trying to access json data from a local server

  • js(folder)
    • item_data.json
    • server.js
    • client.js
  • index.html

In my client.js

var xhttp
window.onload = function(){
  requestData("http://localhost:8000/js/item_data.json");
}

function requestData(URL){
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = processData;
  xhttp.open("GET", URL, true);
  console.log(xhttp);  //it prints information with status: 0
}

function processData(){
  console.log(xhttp.status); //prints 0
  if(xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) { // do something }
  else{ console.log("ERROR"); } //This is always printed
}

In my server.js

const http = require("http");
const file = require("fs");
const host = "localhost";
const port = 8000;

const server = http.createServer(processRequest);

function processRequest(request, response){
  if(request.url === "/index.html"){
    file.readFile('../index.html', 'utf8', function(err, contents) {
      if(err){
        response.writeHead(500, { "Content-Type": "text/html"});
        response.end();
        return;
      }
      response.writeHead(200, { "Content-Type": "text/html"});
      response.end(contents);
  });
  else if(request.url === "/js/item_data.json"){
    file.readFile('item_data.json', 'utf8', function(err, contents) {
        if(err){
          response.writeHead(500, { "Content-Type": "application/javascript"});
          response.end();
          return;
        }
        response.writeHead(200, { "Content-Type": "application/javascript"});
        response.end(contents);
    });
  }
}

I have tried to change the content type to application/json
Tried to use /js/item_data.json
And request.url === "/item_data.json"
They both not working

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!