Reputation: 531
I am trying to read the files from a folder 'data' and the code below should normally work, but I am not able to understand why I am getting this error:
Uncaught TypeError: _fs.readdir is not a function
import fs from "fs";
// Have tried the below option too instead of import sytax
// const fs = require("fs");
const dataFolder = "./data/";
// Option #1
fs.readdir(dataFolder, function (_err, files) {
files.forEach((file) => console.log(file));
});
// OUTPUT
// Uncaught TypeError: _fs.readdir is not a function
// Option #2
fs.readdirSync(dataFolder).forEach((file) => console.log(file));
// OUTPUT
// Uncaught TypeError: _fs.readdirSync is not a function
Any help would be appreciated. I assumed that it was the bundler Parcel that was the cause, but I changed it to Webpack and it was still giving the same error.
Upvotes: 0
Views: 1425
Reputation: 531
I am answering my own question, in case it helps some others like me, who are moving from frontend coding to understanding node.js.
It's difficult to grasp that some modules are just not meant for browsers and fs
is one them and when you try to use 'require' that's another roadblock.. so if, like me, you are here because you tried to use fs
in your javascript linked to your html to read something from your local machine or server and expected it to show up on the browser, it won't work.
It's a bit frustrating but once you get your head around it, it makes sense. So although this might not be the answer you looked for, I thought I'd just share this so that you don't waste more time, trying to make it work.
Getting to understand node.js and how to use fs
on node.js would be better use of time..:-)..
Upvotes: 1