How to get all files in a directory? - reactjs

I have a number of files in a folder in React. Each of them must be self-initialized. For this, I need to import them. I wouldn’t want to import each file individually. I need to get a list of all the files. But we do not have access to FS on the client. I tried this https://github.com/diegohaz/list-react-files solution, but it does not work (it looks like it somehow uses fs, and gives an error). Can I solve my problem in a straightforward way? Can this be done using the web-pack? Any ideas guys?

Yes, we don't have fs on the client so we need to each file manually.
but there is an easy way of doing it.
Make a registry file where you put the path of file from registry.js relative
{
"file1": "/folder1/sda.png",
"file2": "/folder2/asd.png"
}
Now you don't need to import each file manually
import registry.json
import registry from registry.json
for x in registry {
try {
require(`path to registry/${registry[x]}`)
} catch (e) {
console.log(e)
}

Related

Authentication to serve static files on Next.js?

So, I looked for a few authentication options for Next.js that wouldn't require any work on the server side of things. My goal was to block users from entering the website without a password.
I've set up a few tests with NextAuth (after a few other tries) and apparently I can block pages with sessions and cookies, but after a few hours of research I still can't find how I would go about blocking assets (e.g. /image.png from the /public folder) from non-authenticated requests.
Is that even possible without a custom server? Am I missing some core understanding here?
Thanks in advance.
I did stumble upon this problem too. It took my dumbass a while but i figured it out in the end.
As you said - for auth you can just use whatever. Such as NextAuth.
And for file serving: I setup new api endpoint and used NodeJS magic of getting the file and serving it in pipe. It's pretty similar to what you would do in Express. Don't forget to setup proper head info in your response.
Here is little snippet to demonstrate (typescript version):
import { NextApiRequest, NextApiResponse } from 'next'
import {stat} from "fs/promises"
import {createReadStream, existsSync} from "fs"
import path from "path"
import mime from "mime"
//basic nextjs api
export default async function getFile (req: NextApiRequest, res: NextApiResponse) {
// Dont forget to auth first!1!!!
// for this i created folder in root folder (at same level as normal nextjs "public" folder) and the "somefile.png" is in it
const someFilePath = path.resolve('./private/somefile.png');
// if file is not located in specified folder then stop and end with 404
if (! existsSync(someFilePath)) return res.status(404);
// Create read stream from path and now its ready to serve to client
const file = createReadStream(path.resolve('./private/somefile.png'))
// set cache so its proper cached. not necessary
// 'private' part means that it should be cached by an invidual(= is intended for single user) and not by single cache. More about in https://stackoverflow.com/questions/12908766/what-is-cache-control-private#answer-49637255
res.setHeader('Cache-Control', `private, max-age=5000`);
// set size header so browser knows how large the file really is
// im using native fs/promise#stat here since theres nothing special about it. no need to be using external pckages
const stats = await stat(someFilePath);
res.setHeader('Content-Length', stats.size);
// set mime type. in case a browser cant really determine what file its gettin
// you can get mime type by lot if varieties of methods but this working so yay
const mimetype = mime.getType(someFilePath);
res.setHeader('Content-type', mimetype);
// Pipe it to the client - with "res" that has been given
file.pipe(res);
}
Cheers

How would I make a help command that grabs them instead manually?

I'm trying to make a help command that when you use it, instead of having to manually type all the commands, how would I do that? like if I do !help utility how would I grab the utility folder and then get all the commands and list it? i've been trying fs but its confusing with how you would get directs. any help?
You're on the right track with using fs
const fs = require('fs')
// check if that folder exists
if (!fs.existsSync(`../../commands/${args[0]}`))
return message.channel.send('That folder does not exist');
// make array of all files within this folder
const files = fs.readdirSync(`../../commands/${args[0]})
for (const file of files) {
const command = require(`../../commands/${args[0]}/${file}`) // require the file
// now you can do whatever you want with it!
console.log(command.name, command.desription)
};

How can I overwrite an assets image in Flutter having a source image?

I'm fairly new to Dart and Flutter, and I'm having trouble to overwrite an existing assets image from a source image.
My attempt:
try {
File localFile = File('assets/images/myImage.png');
localFile.writeAsBytesSync(originFile.readAsBytesSync());
catch (e) {
log(e.toString());
}
I get:
[log] FileSystemException: Cannot open file, path = 'assets/images/myImage.png' (OS Error: No such file or directory, errno = 2)
I did define the assets folder in pubspec.yaml:
assets:
- assets/images/
Ok, so I've read somewhere that the asset file can be accessed like this:
import 'package:flutter/services.dart' show rootBundle;
final byteData = await rootBundle.load('assets/images/myImage.png');
But I don't know how to convert byteData to a File object that represents the actual file.
I think I'm missing something very basic here. Or maybe is there is a proper way to do this that has nothing to do with this approach?
Please help.
Thanks in advance!
If you want to write a file on a user device you should look here: https://flutter.dev/docs/cookbook/persistence/reading-writing-files
Shared preferences are a space in a phone where you app can write, so it's exactly what you want!
Assets are part of you app and are not meant to be modified within the app.
During a build, Flutter places assets into a special archive called
the asset bundle that apps read from at runtime. According to the flutter website
Hope this helps!

Can we use excel functions in reactjs or jquery?

I need to use all excel functions which return the calculation result. eg. "AverageIf","Decimal".Is there any API or something cdn file which returns all excel functions?
I will be very grateful if someone has information regarding this.
There is a NPM module called hot-formula-parser which may be the thing you're looking for.
Example:
import { Parser } from 'hot-formula-parser';
const parser = new Parser();
parser.parse('SUM(1, 6, 7)');
If you need a list of all formulas supported by the module you can just do:
import { SUPPORTED_FORMULAS } from 'hot-formula-parser';

test database for react-native app development

I'm in the early stages of developing an app with react-native, and I need a DB implementation for for testing and development. I thought that the obvious choice would be to use simple JSON files included with the source, but the only way I see to load JSON files requires that you know the file name ahead of time. This means that the following does not work:
getTable = (tableName) => require('./table-' + tableName + '.json') // ERROR!
I cannot find a simple way to load files at runtime.
What is the proper way to add test data to a react-native app?
I cannot find a simple way to load files at runtime.
In node you can use import() though I'm not sure if this is available in react-native. The syntax would be something like:
async function getTable(tableName){
const fileName = `./table-${tableName}.json`
try {
const file = await import(fileName)
} catch(err){
console.log(err
}
}
though like I said I do not know if this is available in react-natives javascript environment so ymmv
Unfortunately dynamic import not supported by react-native but there is a way so to do this
import tableName1 from './table/tableName1.json';
import tableName2 from './table/tableName2.json';
then create own object like
const tables = {
tableName1,
tableName2,
};
after that, you can access the table through bracket notation like
getTable = (tableName) => tables[tableName];

Resources