List All Files in Directory React - node.js

I am using React.js with Node.js and am trying to serve the client a list of all the files in my (the server's) public folder. I created the app using create-react-app.
I tried using fs but I understood that React is run in a browser environment and that blocks access to file handling so that won't work. After scouring around SO and so many other forums, the closest I got was using require.context but it would return objects with the correct names (of the files) but I couldn't find any way to extract the text from those objects. My code is
const importAll = r => r.keys().map(r);
const files = importAll(require.context('./path/to/folder/', false, /\.*$/));
console.log(files);
I am new to React and web dev in general so I might be missing something.
Thanks in advance!

Related

Uncaught ReferenceError: require is not defined

I have a project by Three.js.
Like below pic, i have an index.html that uses js codes from scripts.js (in sub-Directory of js).
also, this scripts.js , uses three and OrbitControls libs of package of three.js.
PROBLEM:
after running my project, browser, shows HTML and CSS fine, but it do not works by javascript and gives this error:
i can't find any solution, after half a Day searching & manipulating!
can any one help please?
1)project structure:
root
|------server.js
|------/public
| |---index.html
| |---/js/scripts.js
| |---/css/index.css
2)root/public/index.html:
3)root/public/js/scripts.js:
4)root/server.js:
const express = require("express");
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, '/public')));
app.get('/',function(req,res) {
res.sendFile("public/index.html")
});
app.listen(3000, () => {console.log("listening on port 3000");});
Multiple things going on here. First, require() is nodejs ONLY, is not present in the browser. You are trying to load and run js/scripts.js in the browser and thus cannot use require() in that script.
Separately, when you use type="module" in a script tag, that means the module is an ESM module which can use import to load other modules, but import needs to specify a URL that your express server will handle and serve the right file with.
I'm also guessing that you will have a problem loading the script files because they need to be served by express.static() in your server and need to have the appropriate URL paths in your web page so that express.static() will work. You don't show the server-side file structure for all those scripts so it's hard for us to know exactly what the URLs should be.
And, in the future, please don't ever post screen shots of code. That makes it a lot harder for us to use your code in tests or in answers (because we have to retype it all from scratch) and it can't be searched, is harder to read on mobile, etc... Don't put code in images.

NestJs Microservice - Which location do I read files from?

Wondering if anyone can help? I am trying to learn how to use NestJS microservices. I have managed to succesfully get a microservice with MQTT transport setup to receive events from an API. I am trying to use pug to merge the event information with a html template file. However pug cannot find the template file...
this.logger.info(`Running from dir ${__dirname}`); // /usr/src/app/dist/apps/microservice
const template = pug.compileFile('../templates/email.pug');
I have used a logger to display __dirname which refers to the dist directory. This has the single file main.js inside. How do I bundle and read a template pug file from nestjs microservice?
This post has a similar question, however it is for a nestjs app.
First we need to configure the express instance
// main.ts
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
);
app.setViewEngine('hbs');
Put templates folder in root with the neighborhood src folder
but you must find it not in dist folder because Typescript compiler dont copy non-typescript files to dist folder for that approach you can use copy-webpack-plugin
but i just advise you change this url( ../templates/email.pug) so that to find folder located in root not find it in dist
hope it will help you! if not please provide your file structure.
https://docs.nestjs.com/techniques/mvc

Read files from folder before start

I want to get an array of file names from my project public/logos folder. I am using create-react-app template and as you guess, I can not use const fs = require('fs') in browser after project start.
So, is there any way to fill an array right after npm start command and getting file names array from folder or am I out of context?
const fs = require('fs')
const path = require('path')
const appRoot = require('app-root-path').path
const getNames = () => {
fs.readdir(path.join(appRoot, "public", "logos"), (err, files) => {
return files
})
}
Although the Sathishkumar is correct, it's not the only way: having an application server just for reading static images can be too much in many situations.
What you can do is to handle this by change the webpack configuration (this requires you eject first so be really careful).
From webpack you have all of the Nodejs features available but you must make those changes static for the webapp.
An idea:
manually copy with html-copy-plugin every image in the dist folder
read every image file in that folder from node and generate a list of image names
put the list of images as a global variable in your bundle by using webpack DefinePlugin
Now you will be able to read images names from this new global.
Note: this will not be a dynamic read of resources in a folder. If add/remove images you will be forced to repeat the build process of the app.
Yes. It is out of context. Not possible in browser-based JS application. You can't access the file system using Javascript in the browser.
You can use a NodeJS(or any other language for the same) to create a REST API as you mentioned which will return the files list and then can consume it(APIs like fetch or package - axios) in the frontend. This is the preferred way of doing.
If you need to read the files from file system you need to start server, like express, and then read this files on the server by request from frontend or by the link you pasted in your browser address field.

How to send two files from node?

I have two html files.
mynewFile1.html
mynewFile2.html
How to send it to the Angular 4 client from nodejs?
How to get the files in angular 4 which is rendered from back end?
It is pretty simple actually. Just serve the files using static function of express.
var app = express();
app.use(express.static('Files'));//assuming you have the files within the folder Files
Now, you can access your files via angular with the path of the server/filename. For example, if your nodejs api is hosted on http://localhost:4200. Access it in angular using:
http://localhost:4200/mynewFile1.html

How do I prevent Node.js / Express serving up my application's source code?

I never thought this would be a problem with Node.js and Express, but on a crazy whim I decided to type into a browser the location of one of the source files in my Node.js Express project - something like:
http://www.mywebsite.com/mynodejsapp/app.js
To my extreme horror, my application's source code popped right up, publicly available for all to see.
So, that aside: how do I stop it in Node.js / Express?
My setup code is pretty straightforward:
var app = express();
app.configure(function() {
app.use(express.static('/home/prod/server/app/public'));
});
app.listen(8888);
To clarify, this is what my folder structure looks like:
/home/prod/server/
/home/prod/server/app.js
/home/prod/server/public/
All sorts of various files that are intended for public access live under /public. All of my server source code lives under /server/, and my understanding of Express's static folder configuration is that the static folder is the only place that Express happily serves up files from the filesystem from.
Any ideas?
From what you posted it really smells like the URL you entered is served by e.g. Apache/nginx/... and you did put your node app within the document root. The answer is simple in this (and any similar) case:
You never put any of your sourcecode files within the document root or another HTTP-accessible folder. In your case, /home/prod/server/app/public should contain only client-side stuff (HTML, CSS, Graphics, (minified) client-side JS) and nginx should not have anything above this folder as its document root.

Resources