I'm trying to import my code functions from one file to another, however, it's not working.
Look at the file I'm exporting from:
const uri = "mongodb+srv://<User>:<PassWord>#cluster0.ubhacr9.mongodb.net/?retryWrites=true&w=majority"
const client = new MongoClient(uri);
async function run(){
//code
}
async function inserirDatabase(tipo, descricao, valor, id){
//code
}
async function readDatabase (){
//code
}
async function deleteOneOnDatabase(id){
//code
}
module.exports = run, inserirDatabase, readDatabase, deleteOneOnDatabase
Look how I'm importing the file:
import {run, inserirDatabase, readDatabase, deleteOneOnDatabase} from '../database/database.js';
Instead of doing module.exports, try adding "export" before each function name. ie:
export async function run(){
//code
}
Export File:
function somefunction1(){
//codes
}
function somefunction2(){
//codes
}
module.exports = {
somefunction1: somefunction1,
somefunction2: somefunction2
}
Import File:
const {somefunction1, somefunction2} = require("path/to/file.js")
somefunction1()
somefunction2()
Related
I am learning Next.js - version 13 and I try to customize the next.js app base on the standard document. But somehow, the middleware is not called. I assume I do something wrong here. If you have a time, please review the issue.
Here is the code change of middleware.ts:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { AUTHORIZATION_TOKEN, COOKIE_TOKEN } from "#libs/constants";
import { verify } from "#libs/token";
export const config = {
matcher: ["/admin/:path*", "/signin", "/api/:path*"],
};
export async function middleware(request: NextRequest) {
const url = request.nextUrl.clone();
const regex = new RegExp('\\/api\\/(category|product|cart|coupon|auth)\\/(create|update|delete)', 'i')
let matcher: any = regex.exec(url.pathname);
let token: any;
let isValidToken: any;
if (matcher && matcher[0]) {
token = request.headers.get(AUTHORIZATION_TOKEN);
isValidToken = await verify(token);
} else {
token = request.cookies.get(COOKIE_TOKEN)?.value;
if (token) {
isValidToken = await verify(JSON.parse(token));
}
if (url.pathname.startsWith("/admin")) {
if (isValidToken) {
return NextResponse.next();
} else {
url.pathname = "/signin";
return NextResponse.redirect(url);
}
}
if (url.pathname.startsWith("/signin") && isValidToken) {
url.pathname = "/admin";
return NextResponse.redirect(url);
}
}
return NextResponse.next();
}
And the structure of project:
enter image description here
Does someone get any suggestions in this case? If I am wrong, please correct me. Thank you so much.
I had similar issue. I've moved my middleware.ts file in src folder like: /src/middleware.ts and now it's getting called.
According your screenshot, it looks like your middleware.ts is out of /src folder.
Also keep in mind you can't do IO operations like calling DB in that middleware function. Still you can await promises or calling other services via fetch.
I am noob with JS and I can't figure how to instantiate one of my objects in this jest unit test (backend / nodejs project)
project structure:
appi/
src/
configFactory.js
...
test/
configFactory.test.js
...
package.json
Using require
configFactory.js
class ConfigFactory {
constructor(index_mapping){
this.mapping = index_mapping
}
}
configFactory.test.js
const ConfigFactory = require('../src/configFactory.js')
var fs = require('fs');
test('some test', () => {
fs.readFile(__dirname +'/__mock-data__/Mappings/mappings_ac.json', 'utf8', function(err, data) {
if (err) throw err;
const factory = new ConfigFactory(data);
});
});
This ends up with a TypeError: ConfigFactory is not a constructor
Using import
class ConfigFactory {
constructor(index_mapping){
this.mapping = index_mapping
}
}
export default ConfigFactory
import ConfigFactory from "../src/configFactory"
ends up with SyntaxError: Cannot use import statement outside a module. I tried to add "type": "module" to package.json but I feel that I am missing an important point
Looks like I was not properly exporting my class for CJS:
class ConfigFactory {
constructor(index_mapping){
this.mapping = index_mapping
}
}
module.exports = ConfigFactory
I'm doing the server side of the site on the Adonis JS framework.
I have been tasked with loading large files, to solve this problem I decided to use file loading by chunks.
I have found some client-side code and it seems to work.
Here is the code on client side: https://codepen.io/chaly7500/pen/YzQyZNR
The code on the server side:
//routes.ts.
apiGroup('v1', 'files', Route.group(async () => {
Route.post('upload', 'Files/UploadController.index')
}))
//UploadController.ts.
'use strict'
import {HttpContextContract} from "#ioc:Adonis/Core/HttpContext";
import MediaRepositories from "App/Repositories/MediaRepositories";
export default class UploadController {
public async index({request}:HttpContextContract){
const file = request.file('file')
// console.log(file)
return await MediaRepositories.createMedia(file)
}
}
//MediaRepositories.ts
'use strict'
Import Application from "#ioc:Adonis/Core/Application";
export default class MediaRepositories {
static async createMedia(file) {
await file.move(Application.publicPath('media/transientmodels'))
}
static async updateMediaById(){
}
static async updateMediaByIds(){
}
}
After uploading to the server, I have a blob file
And when I change the blob file to blob.png the image breaks
Has anyone implemented uploading large files using AdonisJS?
Or how to correctly convert blob file to image or video?
Main question:
How to upload big files to adonis and not get request timeout error ?
I was able to solve the loading problem with this library
https://www.npmjs.com/package/file-chunked
//UploadController.ts
'use strict'
import {HttpContextContract} from "#ioc:Adonis/Core/HttpContext";
import parseJson from "parse-json";
import MediaRepositories from "App/Repositories/MediaRepositories";
export default class UploadController {
public async index({request}:HttpContextContract){
const file = await request.file('file')
const chunkMetaDataStr = await request.input('chunkMetadata');
const chunkMetaData = await parseJson(chunkMetaDataStr);
return await MediaRepositories.createMedia(file, chunkMetaData)
}
}
// MediaRepositories.ts
'use strict'
import Application from "#ioc:Adonis/Core/Application";
import FileChunked from "file-chunked";
import * as fs from "fs";
import Media from "App/Models/Media";
import Env from '#ioc:Adonis/Core/Env'
export default class MediaRepositories {
static async createMedia(file, chunkMetaData) {
await file?.move(Application.publicPath('media/transientmodels/' + chunkMetaData.FileGuid + '/tmp_chunks'));
await FileChunked.upload({
chunkStorage: Application.publicPath('media/transientmodels/' + chunkMetaData.FileGuid), // where the uploaded file(chunked file in this case) are saved
uploadId: chunkMetaData.FileGuid,
chunkIndex: chunkMetaData.Index,
totalChunksCount: chunkMetaData.TotalCount,
filePath: file?.filePath,
});
if (chunkMetaData.Index == (chunkMetaData.TotalCount - 1)) {
fs.copyFileSync(Application.publicPath('media/transientmodels/' + chunkMetaData.FileGuid + '/tmp_chunks/' + file.clientName),
Application.publicPath('media/transientmodels/' + chunkMetaData.FileGuid + '/tmp_chunks/' + chunkMetaData.FileName));
}
}
}
Maybe i asked wrong question.
i'm trying to test some site, and have this throw in terminal
terminal output
it's obvious, that function returns uuid after it was called in code.
it work's normaly, when i take element right in code, so the reason, i think, in uncorrect import
here's my code :
file.js
describe('final homeTask', () => {
it('firstassigment', async () => {
let mainPage = require('../page/main.pageHW.js')
await browser.url('https://github.com/')
let signUpButton = await mainPage.topSignUpBtn()
await signUpButton.click()
})
})
main.pageHW.js
class MainPage {
get topSignUpBtn () { return $('a.btn-mktg:nth-child(1)') }
}
module.exports = new MainPage()
It is a problem with Javascript, not about webdriver, you are using a property in the MainPage class:
class MainPage {
/// The get word make it a property
get topSignUpBtn () { return $('a.btn-mktg:nth-child(1)') }
}
module.exports = new MainPage()
That means you DON'T need parentheses to use it, so, replace:
let signUpButton = await mainPage.topSignUpBtn()
By
let signUpButton = await mainPage.topSignUpBtn;
Also, the property doesn't need the await clause.
If you want more info you can check this link.
I have two files in nodejs :
index.js
function.js
The index.js is my main file in which i call the functions inside function.js. In function.js i need to use logging, the problem is i didn't figure out how to use it.
function.js
module.exports = {
Exemplfunciton: async () => {
app.log('#### This is just an exemple im trying to run')
}
checkCalcul:async(a,b) = > {
log.(`The Val of A : ${a}, the Val of B: ${b}`
return a+b
}
}
index.js
const functionToCall = require('/function.js)
module.exports = app => {
functionToCall.Exemplfunciton()
functionToCall.checkCalcul(4,5)
}
Will return
app is not defined
tried it without the app in the function.js it returned to me
log not defined.
I only need to use the app.log between the functions ( my main one the index.js and the function.js )
Pass as an argument
module.exports = app => {
functionToCall.Exemplfunciton(app) // add here
}
Then consume
module.exports = {
Exemplfunciton: async (app) => { // add here
app.log('#### This is just an exemple im trying to run')
}
}
To log in Node.js, you should use console https://nodejs.org/api/console.html
Example
module.exports = {
ExampleFunction: async () => {
console.log('#### This is just an example I\'m trying to run')
}
}
const functionToCall = require('./function.js')
functionToCall.ExampleFunction() // logs #### This is just an example I\'m trying to run
Consider extracting the log functionality out into its own file that can be referenced by function.js, index.js, and anything else in your app. For example:
logger.js
module.exports = {
log: function() {
/* aggregate logs and send to your logging service, like TrackJS.com */
}
}
function.js
var logger = require(“./log.js”);d
module.exports = {
exampleFunction: function() {
logger.log(“foo bar”);
}
};
index.js
var functions = require(“./functions.js”);
var logger = require(“./log.js”);
functions.exampleFunction();
logger.log(“foo”);
You should send the logs off to a service like TrackJS to aggregate, report, and alert you to production problems.