importing and exporting es6 classes - javascript

I want to create ES6 class that reads data from a file and simply returns the content of the file, so I created a class called FileReader which has a constructor filePath and has a method called getFileContent
import fs from 'fs';
import path from 'path';
export class FileReader {
constructor(filePath) {
this.filePath = filePath;
fs.readFile(filePath, (err, data) => {
if (err) {
console.log(err);
}
this.fileContent = data;
});
}
getFileContent(separator, columns) {
console.log(this.fileContent);
}
}
I have a react component called OrderList I want to use FileReader inside componentDidMount method to read the content of the file
import React from 'react';
import {FileReader} from '../Utils/FileReader';
class OrdersList extends React.Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
FileReader reader = new FileReader('');
reader.getFileContent(',' , []);
}
render() {
}
}
export default OrdersList;
the problem that I'm getting an error Unexpected token reader so what's wrong with this approach ?

change this line: FileReader reader = new FileReader(''); to const reader = new FileReader('');

There are two problems in your code:
You're reading file content in the constructor, in the most of the cases, fileContent will be undefined, because fs.readFile is async function.
You're creating a reader without file path: FileReader reader = new FileReader('');
To fix described problems you should move the logic for reading file in class function and use callback or promise:
class OrdersList extends React.Component {
constructor(filePath) {
this.filePath = filePath;
}
getFileContent(separator, columns, cb) {
fs.readFile(this.filePath, (err, data) => {
if (err) {
console.log(err);
}
cb(err, data) ;
});
}
}
In OrdersList you should use real file name and call function with callback to read file content:
class OrdersList extends React.Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
let reader = new FileReader(realFilePath);
reader.getFileContent(',' , [], (err, content) => {
// TODO: file content in content var
});
}
}

Related

Unable to upload image and save to a folder using react

I am trying to upload the image in react, I used the extension ** react-image-upload**.
I used this code to show images on a webpage
import React from 'react';
import ImageUploader from 'react-images-upload';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { pictures: [] };
this.onDrop = this.onDrop.bind(this);
}
onDrop(pictureFiles, pictureDataURLs) {
this.setState({
pictures: pictureFiles
});
}
render() {
return (
<ImageUploader
withIcon={true}
buttonText='Choose images'
onChange={this.onDrop}
imgExtension={['.jpg', '.gif', '.png', '.gif']}
maxFileSize={5242880}
/>
);
}
}
Now The image is showing on the webpage but I don't know how to upload it and save it to a folder I am trying to use this code.
This line is for onChange
onDrop(pictureFiles, pictureDataURLs) {
this.setState({
picture: pictureFiles
});
}
This line is uploading the image, but I don't know how it will function and if I need to add the backend.
uploadHandler = () => {
const formData = new FormData();
formData.append('file', this.state.picture);
console.log()
let context = 'profile';
service.uploadImage(formData,
this.state.picture,
context, (res) => {
if (res.status === "ERROR") {
console.log("ERROR: ", res);
stopLoading();
}
});
}
And the upload function -
export const uploadImage = (file, fileName, context, onDone) => {
console.log(fileName)
post(encodeURI("/api/upload-files/" + fileName + "/" + context), file, (res) => {
onDone(res.data);
});
};
And the backend code, I am using FastAPI- Python for it-
#router.post("/upload-files")
async def image(image: UploadFile = File(...)):
print(image.filename)
return {"filename": image.filename}
I checked the values and the results are right on backend but on webpage it is showing 422: preprocessing error.
Please give some idea what's the process or some hint so I can complete the code.

Javascript: Fetch data while executing code

I am building an app that relies on some data I need to fetch from my server. Right now my app starts with fetching the data and then passing down the data through several steps which are separated by classes. I simplify the code in the following.
Class1:
export default class Class1 {
constructor(props) {
this.props = props
}
async init() {
const data = await this.fetchData()
new Screen({ data }).init()
}
async fetchData() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open("POST", 'http://localhost:8888/getData', true)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onload = () => resolve(JSON.parse(xhr.responseText))
xhr.onerror = reject
xhr.send(JSON.stringify({}))
})
}
}
Class2:
export default class Screen {
constructor(props) {
this.props = props
}
async init() {
let ScreenType
if (this.offscreenIsSupported()) ScreenType = Offscreen
else ScreenType = Onscreen
new ScreenType(this.props).init()
}
offscreenIsSupported() {
return "OffscreenCanvas" in window && "transferControlToOffscreen" in this.props.canvas
}
}
OnscreenClass:
export default class Onscreen {
constructor(props) {
this.props = props
}
async init() {
new Handler(this.props}).init()
}
}
OffscreenClass:
export default class Offscreen {
constructor(props) {
this.props = props
}
async init() {
this.worker = new Worker(new URL('./offscreen.worker.js', import.meta.url))
const offscreen = this.props.canvas.transferControlToOffscreen()
this.worker.postMessage({
type: "init",
canvas: offscreen
}, [offscreen])
}
}
offscreen.worker.js
self.onmessage = msg => {
switch (msg.data.type) {
case 'init':
init(msg.data)
break
}
}
async function init(data) {
self.vgHandler = new Handler({ data })
await self.vgHandler.init()
}
Class3:
export default class Handler {
constructor(props) {
this.props = props
}
async init() {
this.setup(this.props.data)
}
}
As you can see the main code called in Class3 will be the same. This Class needs the fetched data. Class2 is just necessary to determine if the browser should use offscreen or onscreen canvas. Since checking the ability of using offscreen canvas as well as creating the web worker is not dependent to the fetched data it is not very smart to await the fetching process.
How am I able to fetch the data in background, run my code of Class2 simultaneously and use the fetched data in Class3?
I want to make this process as fast as possible.
Best

how to read ts file and update code dynamically using fs?

i am scaffolding new project using yeoman generator it is creating all the directories and running dependencies , now once files are generated i want to update js class same as appName,
first i am trying to read the ts file which i failed to do it throws error TypeError: Cannot read property 'toString' of undefined then i would update the file with appName if there is any better approach to achieve this task i will apprecaite the help.
index.js
updateTsFile () {
const npmdir = `${process.cwd()}/${this.props.appName}`;
const dirPath = `${npmdir}/${"./api.ts"}`;
console.log("path", dirPath);
let response;
_fs.readFile(dirPath, (_err, res) => {
if (_err) {
console.error(_err);
}
let file = res.toString("utf-8");
console.log(file);
response = file;
let lines = file.split("\n");
for (let i = 0; i < lines.length; i++) {
console.log(lines[i]);
}
});
return response;
}
api.ts
export class CAPIClass extends Wrapper {
public after = after;
constructor() {
super({
configFileName: "package-name-v1.json"
});
}
}
expected output
export class CMyAppNameClass extends Wrapper {
public after = after;
constructor() {
super({
configFileName: "package-name-v1.json"
});
}
}
In case of an error you're just logging the error but continuing with the logic. So it seems like you're running into an error resulting in res being undefined. Since fs exposes a promise-based api nowadays, I would rewrite this as follows instead of using callbacks (also note that you were using utf-8 for the encoding but it should be utf8):
async updateTsFile() {
const npmdir = `${process.cwd()}/${this.props.appName}`;
const dirPath = `${npmdir}/${"./api.ts"}`;
console.log("path", dirPath);
try {
const fileData = await _fs.promises.readFile(dirPath);
const fileAsStr = fileData.toString("utf8");
// replace class-name
fileAsStr = fileAsStr.replace(/CAPIClass/g, "CMyAppNameClass");
// (over)write file: setting 'utf8' is not actually needed as it's the default
await _fs.promises.writeFile(dirPath, fileAsStr, 'utf8');
} catch (err) {
console.log(err);
// handle error here
}
}

kuzzle / react native - Cannot inherits class from BaseController

I'm trying to extends the KUZZLE JavaScript SDK in order to call some controllers on kuzzle servers, implemented via plugins.
I'm following that guide: add controller
Here is my controller which extends from the BaseController:
const { BaseController } = require('kuzzle-sdk');
export class UserController extends BaseController {
constructor (kuzzle) {
super(kuzzle, 'plugins-user/userController');
}
/**
* Method to call the action "CreateAccount" on the UserController
* #param {*} user
*/
async createAccount(user) {
const apiRequest = {
action: 'new',
body: {
user
}
};
try {
const response = await this.query(apiRequest);
return response.result.user;
}
catch (error) {
//Manage errors
}
}
}
And here is where I specify the controller in order to use it further in the App, on the creation of the singleton.
const {UserController} = require('./UserController');
const { Kuzzle, WebSocket } = require('kuzzle-sdk');
class KuzzleService {
static instance = null;
static async createInstance() {
var object = new KuzzleService();
object.kuzzle = new Kuzzle(
new WebSocket('localhost'),{defaultIndex: 'index'}
);
object.kuzzle.useController(UserController, 'user');
await object.kuzzle.connect();
const credentials = { username: 'admin', password: 'pass' };
const jwt = await object.kuzzle.auth.login('local', credentials);
return object;
}
static async getInstance () {
if (!KuzzleService.instance) {
KuzzleService.instance = await KuzzleService.createInstance();
}
return KuzzleService.instance;
}
}
export default KuzzleService;
Somehow I'm getting the following error:
Controllers must inherit from the base controller
Is there something wrong with the imports ?
I've found out the solution to that issue. Firstly, I was not on the right version of the kuzzle SDK released recently (6.1.1) and secondly the controller class must be exported as default:
const { BaseController } = require('kuzzle-sdk');
export default class UserController extends BaseController {
constructor (kuzzle) {
super(kuzzle, 'plugins-user/userController');
}
/**
* Method to call the action "CreateAccount" on the UserController
* #param {*} user
*/
async createAccount(user) {
const apiRequest = {
action: 'new',
body: {
user
}
};
try {
const response = await this.query(apiRequest);
return response.result.user;
}
catch (error) {
//Manage errors
}
}
}
And then the UserController needs to be importer that way:
import UserController from './UserController.js'
Then, as specified in the documentation, we need just inject the kuzzle object into the controller that way:
kuzzle.useController(UserController, 'user');

Resolve a AsyncStorage promise inside componenDidMount

I'm trying to check if a user is authenticated. I do this by checking some record in asyncStorage, I have the following code
App.js
let AuthService = require('./app/layouts/AuthService/AuthService.js');
export default class App extends React.Component {
componentDidMount() {
AuthService.getAuthInfo((err, authInfo) => {
this.setState({
checkingAuth: false,
isLoggedIn: authInfo != null
})
});
}
}
Auth.js
'use strict';
let AsyncStorage = require('react-native').AsyncStorage;
let _ = require('lodash');
const authKey = 'auth';
const userKey = 'user';
class AuthService {
getAuthInfo(cb){
AsyncStorage.multiGet([authKey, userKey], (err, val)=> {
if(err){
return cb(err);
}
if(!val){
return cb();
}
let zippedObj = _.zipObject(val);
if(!zippedObj[authKey]){
return cb();
}
let authInfo = {
header: {
Authorization: 'Basic ' + zippedObj[authKey]
},
user: JSON.parse(zippedObj[userKey])
}
return cb(null, authInfo);
});
}
}
module.exports = new AuthService();
In app.js, I'm trying to use this function from Auth.js, but I get no response from the fuction, I get console logs from getAuthInfo before I get into the AsyncStorage function. Im pretty new to react-native and ES6, and I think is a promise or async problem but I cant make it work. In app.js im redering a ActivityIndicator so I dont block the UI with checkingAuth and isLoggedIn.
I tried to use some .then in app.js with no results.
First of all, you return your callback function instead of calling it. Try to call it by removing return like this : cb(null, authInfo);.

Categories

Resources