node.jsexpressnode.js-fs

Read a Java file using fs module (express.js)


I'm trying to use express's fs module to scan text files and display them on screen. I managed to do this in my tests using a txt file, but I'm having trouble getting the same code to work with java files.

Is it possible to read a java file or can the module only read txt files?

Basicly, my code is this:

async function readFile(req, res) {
    const filePath = path.join('C:/Users/Tester/Desktop/Test', 'Text.txt');

    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) {
            console.error(err);
            return res.status(500).send('Error while reading file');
        }
        res.send(data);
    });
}

I just tried swapping the path field for the new field of a java project and the name of the file I want to read.

Thank you in advance for your help!


Solution

  • In my case, the problem is related to the path specified. The path is incorrect because of the way escape characters are treated in JavaScript strings. When you use \ in a JavaScript string, it is treated as an escape character. For example, \n represents a new line. If you want to include a literal \ in a file path, you need to escape it, i.e. use \\.

    After correcting this, my code worked