0

I'm trying to understand how can I read a file in js So I start to use node js for use the fs package

So I'm doing some thing like this, it works :

var fs = require('fs');

function allTopics() {
    const result = new Map();
        try {
            const fileContent = fs.readFileSync( "../svg/plan.svg","UTF-8");
            const lines = fileContent.split("\n");
            const listTickets = retrieveTopic(lines);
            listTickets.forEach(function (value, i) {
                result.set(i, value);            
            });
        } catch (err) {
            return Promise.reject("ERROR: Cannot find file");
        }
        console.log(result);
        return result;
}

function retrieveTopic(lines) {
    const listTopic = [];
    lines.forEach((line) => {
        const topicMatch = line.match(/\{[\w\/]+\}/g); 
                if (topicMatch) {
                    listTopic.push(topicMatch[0]);
                }
    })
    return listTopic;
}

allTopics();
module.exports = { allTopics };

So now what I want, it's to use this but into a html file for see in browser into console :

<script>
function allTopics() {
    const result = new Map();
        try {
            const fileContent = fs.readFileSync( "../svg/plan.svg","UTF-8");
            const lines = fileContent.split("\n");
            const listTickets = retrieveTopic(lines);
            listTickets.forEach(function (value, i) {
                result.set(i, value);            
            });
        } catch (err) {
            return Promise.reject("ERROR: Cannot find file");
        }
        console.log(result);
        return result;
}

function retrieveTopic(lines) {
    const listTopic = [];
    lines.forEach((line) => {
        const topicMatch = line.match(/\{[\w\/]+\}/g); 
                if (topicMatch) {
                    listTopic.push(topicMatch[0]);
                }
    })
    return listTopic;
}

The problem is that you can't use fs into browser, so I can read a file and see the output into a browser console

I don't wanna use something like input and then choosen file

Thanks for your help

zefzef aa
  • 67
  • 6
  • 1
    You can't read files from the disk with the browser, that would be a huge security risk. – cloned Jul 21 '21 at 11:14
  • You just want to display an image from an existing file?.. – Chrillewoodz Jul 21 '21 at 11:15
  • In the default settings, as @cloned mentioned, it will be a huge security risk if the browser can access your files directly, however, going through the select file route, here is a good reference : https://www.geeksforgeeks.org/how-to-read-a-local-text-file-using-javascript/ – tsamridh86 Jul 21 '21 at 11:15
  • 1
    Input is the only way to go in a standard website and standard browser. However, UX can be customized with "drag an drop" and other similar strategies. – Ernesto Stifano Jul 21 '21 at 11:17

0 Answers0