I am new in ES6 in ES5 I was able to set property of any require(imported) package something like this
var client = require('./client');
var conn = require('./conn/conn1.js');
client.conn = conn;
module.exports = client;
and in client package we were able to access client.conn. LIke this
function client(opts){
// client.conn is accesable here
}
Now in ES6 I am trying to do like this
import client from './client'
import conn from './conn/conn1.js'
client.conn = conn;
export {client as default}
But I am not able to access conn variable. How can I do it in the right way.
You can import the function direclty as import {client} from './client' this way the only thing that you will be importing of the client.js will be the client fucntion.
see: import statements
Related
I'm working in MySQL Database class. In React Project, I can instantiate a File([Blob],filename). But in the Express Backend project, I can't use File module. It show an error as ReferenceError: File is not defined. I don't know how to use them without importing like the React project.
Here is my code for instantiating the File() Object. I tried to import it from "buffer"
downloadProfile = (id,success) => {
this.db.query(`SELECT pi.Filename, pi.Data AS Buffer, pi.MIME, pd.Data FROM profile_image AS pi JOIN profile_data AS pd ON pi.UserID = pd.UserID WHERE pi.UserID = ? AND pd.UserID = ?`,
[id,id],(err,result)=>{
if (err) throw err
const filename = result[0]["Filename"]
const buffer = result[0]["Buffer"]
const mime = result[0]["MIME"]
const image = this.getImageBase64(buffer,mime)
const imageBlob = new Blob([buffer],{type:mime})
const iamgeFile = new File([imageBlob],filename,{type:mime})
const data = JSON.parse(result[0]["Data"])
success({["Data"]:data,["Image"]:image})
})
}
In addition, which one between CommonJS and Module that recommend to working with Node.js Express project.
I need to scrape some data for the Dart / Flutter application and I need to log in to access the page.
How do I submit changes to the form data and click on the login button? I tried as follows:
var loginPage = await http.get('https://mypage.com/login');
var document = parse(loginPage.body);
var username = document.querySelector('#username') as InputElement;
var password = document.querySelector('#password') as InputElement;
username.value = 'USERNAME';
password.value = 'PASSWORD';
var submit = document.querySelector('.btn-submit') as ButtonElement;
submit.click();
But I have the following error:
Error: 'InputElement' isn't a type.
Error: 'ButtonElement' isn't a type.
I also tried the following:
InputElement username = document.querySelector('#username');
But a get the error A value of type 'Element' can't be assigned to a variable of type 'InputElement'
I need to make this scrape in the flutter application to avoid passing the password using API.
How can I log in to the page to get the data?
InputElement and ButtonElement are part of the dart:html package, therefore, we shouldn't forget to import it in our code:
import 'dart:html';
import 'package:http/http.dart' as http;
void submitForm() async {
var loginPage = await http.get('https://mypage.com/login');
var document = parse(loginPage.body);
var username = document.querySelector('#username') as InputElement;
var password = document.querySelector('#password') as InputElement;
username.value = 'USERNAME';
password.value = 'PASSWORD';
var submit = document.querySelector('.btn-submit') as ButtonElement;
submit.click();
}
By doing so, the compiler will recognize InputElement and ButtonElement as correct types.
Another, more elegant, way to obtain the same result would be:
import 'dart:html';
import 'package:http/http.dart' as http;
void submitForm() async {
var loginPage = await http.get('https://mypage.com/login');
Document document = parse(loginPage.body);
(document.querySelector('#username') as InputElement).value = 'USERNAME';
(document.querySelector('#password') as InputElement).value = 'PASSWORD';
(document.querySelector('.btn-submit') as ButtonElement).click();
}
If we'd like to use the same functionality in a Flutter project, we might need the help of the universal_html package:
Add this to your package's pubspec.yaml file:
dependencies:
universal_html: ^1.2.3
Run flutter pub get
Import the package and use the code:
import 'package:http/http.dart' as http;
import 'package:universal_html/html.dart';
void submitForm() async {
var loginPage = await http.get('https://mypage.com/login');
Document document = parse(loginPage.body);
(document.querySelector('#username') as InputElement).value = 'USERNAME';
(document.querySelector('#password') as InputElement).value = 'PASSWORD';
(document.querySelector('.btn-submit') as ButtonElement).click();
}
I am trying to import a CSV for use with the D3 library to create a chart within a Create React App project, but importing the file is throwing a "Cannot find module" error even though the path to the CSV file is correct.
I have a feeling this might be something to do with CRA's Webpack config under the hood but it looks like this is using the file loader so I'm not sure what the issue is. The data file is within CRA's src directory.
The console log in the code below is running with the correct data in, which means the data must be being accessed. The error is thrown after this (Although the path to the CSV is underlined red in my editor).
I am using TypeScript but I don't think this has anything to do with the problem.
import React from 'react';
import * as d3 from 'd3';
import CSVData from '../data/data.csv';
const BarChart: React.FC = () => {
d3.csv(CSVData).then(res => {
console.log(res);
});
return <div>Test</div>;
};
export default BarChart;
CRA doesn't support importing .csv files. Without ejecting from CRA, your best option is to copy that file along with the results of yarn/npm build to your web server and then fetching it at runtime.
If that CSV is big (more than a few kb), then it is also the better option in terms of performance/code splitting.
Thanks to Nick Ribal for his answer, I found a similar solution by moving my data file into the public folder and then referencing this via the PUBLIC_URL environment variable.
I used the D3 CSV method which will get data from a URL if passed one rather than using fetch and parsing this as text.
With D3 CSV method:
import React, { useState } from 'react';
import { DSVRowArray } from 'd3';
import * as d3 from 'd3';
type CSVData = DSVRowArray | null;
const BarChart: React.FC = () => {
const initialState: CSVData = null;
const [fetchedCSVData, setFetchedCSVdata] = useState<CSVData>(initialState);
if (!fetchedCSVData) {
d3.csv(`${process.env.PUBLIC_URL}/data/data.csv`).then(res => {
setFetchedCSVdata(res);
});
}
return <div>Test</div>;
};
export default BarChart;
Without D3 CSV method:
import React, { useState } from 'react';
type CSVData = string | null;
const BarChart: React.FC = () => {
const initialState: CSVData = null;
const [fetchedCSVData, setFetchedCSVData] = useState<CSVData>(initialState);
if (!fetchedCSVData) {
fetch(`${process.env.PUBLIC_URL}/data/data.csv`)
.then(res => res.text())
.then(stringData => {
console.log(stringData);
setFetchedCSVData(stringData);
});
}
return <div>Test</div>;
};
export default BarChart;
Im setting my store on my react native app, is working fine with redux-dev-tools,
but I dont know how to refactor.
const store = createStore(reducer, /* preloadedState, */
composeEnhancers(
applyMiddleware(...middleware)));
const configureStore = () => {
return store;
};
export { configureStore };
The goal is to export only "store" as a function
Why do you want to export store as a function as you could just as well export it as an object?
export const store = configureStore();
This way you could also just import it in any file you like:
import { store } from '...';
// Now you can access the redux store and dispatch actions:
store.getState() ...
store.dispatch(...)
Hi I am trying to run mocha and chai test to test my node js router, which saves a user in mysql database and then returns the same array back.
The problem I am facing at the moment is that I would not like to save the information in the database when I run it from local and when I use a continious integration software like travis/Ci the test fails since there is no database connection. I would like to know how can I test the database saving with the current without actually saving to the database.
Basically meaning having a fake virtual database to save or returning save.
I read that sinon.js can help but I am quite not sure on how to use it.
Here is my code
var expect = require('chai').expect;
var faker = require('faker');
const request = require('supertest');
const should = require('should');
const sinon = require('sinon');
const helper = require('../../models/user');
describe('POST /saveUser',()=>{
it('should save a new user',(done)=>{
var fake =
request(app)
.post('/saveUser')
.send({
Owner : faker.random.number(),
firstname : faker.name.firstName(),
lastname : faker.name.lastName(),
email:faker.internet.email(),
password : faker.random.number(),
token : faker.random.uuid()
})
.expect(200)
.expect((res)=>{
expect(res.body.firstname).to.be.a("string");
expect(res.body.lastname).to.be.a("string");
expect(res.body.Owner).to.be.a("number");
})
.end(done);
});
});
This is the router
router.post('/saveUser',(req,res,next)=>{
saveUser(req.body).then((result)=>{
return res.send(req.body);
}).catch((e)=>{
return res.send('All info not saved');
});
});
And here is the model
saveUser = (userinfo) => new Promise((resolve,reject)=>{
db.query('INSERT INTO user SET ?',userinfo,function(error,results,fields){
if(error){
reject();
}else{
resolve(userinfo);
}
})
});
What you are describing is a stub. With sinon you can stub methods and call fake methods instead like this:
sinon.stub(/* module that implements saveUser */, 'saveUser').callsFake(() => Promise.resolve());