'How to use FS from NodeJs ? "I'm `FS` modules"

Before asking I read alot in this same forum about this problem and couldn't find a solution.

This is my js file:

const fs = require( 'fs' );

fs.readFile( './test.html', (err, data) => {
   if (err) throw err;
   console.log(data);
})

And this is the result: "I'm fs modules"

I read that this is because this is not the native "fs" package from NodeJs and that I might have a "troll" one.

Alright, I did

npm uninstall fs
npm uninstall -g fs

Still the problem remains. So I uninstalled NodeJs completely from my machine, restart, installed again, restart again and still the same issue.

I have no problem with the "http" package for example.

My version of npm - 6.14.11, node - 14.15.4, webpack - 4.46.0

I'm stuck on this on I have the feeling that I am being trolled or just missing something absolutely obvious.

Can you please help me resolve this ?



Solution 1:[1]

According to the webpack error it seems that You are trying to use fs inside a browser. Browser JavaScript can't access file system so fs package will not load. Instead of using file api try to send an http request to the server and respond with corresponding data.

Solution 2:[2]

  1. npm init
  2. mkdir
  3. install axios
  4. touch index.js
  5. copy past betow code
  6. run node index.js
const fs = require('fs');
const axios = require('axios').default;
axios.get('https://drive.google.com/file/d/1I7ec--mRp-e93mM7Hm50PAQXtFP-cviR/view?usp=sharing').then((res) => {
    fs.writeFile('abc.txt', res.data, (err, data) => {
        if (err) {
            console.error(err);
        } else {
            console.log("File created successfully");
            fs.open('abc.txt', 'r+', (err, fd) => {
                if (err) {
                    console.error(err);
                } else {
                    console.log('file opened');
                    fs.readFile('abc.txt', 'utf-8', (err, data) => {
                        if (err) {
                            console.error(err);
                        } else {
                            console.log("Read");
                            fs.close(fd, (err, data) => {
                                if (err) {
                                    console.error(err);
                                } else {
                                    console.log("Closed");
                                }
                            })
                        }
                    })
                }
            })
        }
    })
})

//Output

/* 
File created successfully
file opened
Read
Closed
*/


  1. List item

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hopeless-programmer
Solution 2