0

I am trying to read a file content based on a GET request with the file name as an input parameter: My code should support nested folders also. If the file is not present then I want to return 404, for any other error I want to return 500.

This is my code:

const loadData = (folderPath) => {
    //here my code:
    fs.readFileSync(path.join(_dirname, folderPath));
}

I get an error saying _dirname is not defined.

This is my test code:

const get = (file) => new Promise((resolve, reject) => {
    return http.get(`http://localost:3000/${file}`, res => {
        let data = "";
        let statuc = res.statusCode;
        
        res.on('data', function(chunk) {
            data += chunk;
        });
        
        res.on('end', function() {
            resolve({data, statuc});
        });
    });
});


const server = loadData('tmp/myapp/public');
const port = process.env.PORT || 3000;

server.listen(port);

get('myfile.txt').then(data => {
    console.log(data);
    server.close();
});
learner
  • 6,062
  • 14
  • 79
  • 139
  • I can't understand from your code what you are trying to achieve. I suggest you start out by building a simple server app that just returns a text response, and a separate client app that sends a request to the server and logs the response. There are plenty of examples of simple client/server apps in Node.js tutorials, including how to send errors from the server to the client. Then, once you have that working, start adding in the logic for reading the file in the server app. – JohnRC Aug 07 '22 at 17:31
  • @JohnRC, yes I have tried those examples, but in this task I want to read the file contents from the folder path provided using a GET request. I am not able to understand how I can do with nodejs – learner Aug 07 '22 at 19:11
  • @learner is it you answer? https://stackoverflow.com/questions/10434001/static-files-with-express-js – Nikita Aplin Aug 08 '22 at 07:57

1 Answers1

0

There are many errors, for example: loadData is wrong:

  • You are not returning anything.
  • __dirname and not _dirname
// this should "work", it depends on what you want to do
const loadData = (folderPath) => {
    //here my code:
    return fs.readFileSync(path.join(__dirname, folderPath));
}

Also.

const get = (file) => new Promise((resolve, reject) => {
    return http.get(`http://localost:3000/${file}`, res => {
        let data = "";
//        let statuc = res.statusCode; // not needed, use directly
        
        res.on('data', function(chunk) {
            data += chunk;
        });
        
        res.on('end', function() {
            resolve({data, res.statusCode});
        });
    });
});


const server = loadData('tmp/myapp/public'); // your functions is not a server like `express`, maybe you are copy-pasting wrong?

const port = process.env.PORT || 3000;

server.listen(port);

get('myfile.txt').then(data => {
    console.log(data);
    server.close();
});
Diego Betto
  • 721
  • 6
  • 19