How can I use audio files in next.js13? - next.js13

I am trying to use audio files in Next.js 13, "You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)" This error occurs.
What should I do?
SoundComponent
"use client";
import tickSound from "../../sounds/tick1.wav";
export default function Sound() {
const tick = new Audio(tickSound);
const metronomeSoundHandler = () => {
tick.play();
};
return (
<>
<button onClick={metronomeSoundHandler}>Play</button>
</>
);
}
Next.config.js
/** #type {import('next').NextConfig} */
const nextConfig = {
experimental: {
appDir: true,
},
}
module.exports = nextConfig
I want to use audio file

Related

Cypress - How can I add assertion for downloaded file contains name that is dynamic?

In cypress, the xlsx file I am downloading always starts with lets say "ABC" and then some dynamic IDs like ABC86520837.xlsx. How can I verify and add assertion that if the file is downloaded successfully and also contains that dynamic name?
You'll need to create a task to search within file directory of your machine and then return a list of matching downloads to assert. You'll also need globby to make it easier.
In your plugins/index.js
async findFiles (mask) {
if (!mask) {
throw new Error('Missing a file mask to search')
}
console.log('searching for files %s', mask)
const list = await globby(mask)
if (!list.length) {
console.log('found no files')
return null
}
console.log('found %d files, first one %s', list.length, list[0])
return list[0]
},
In your spec file:
const downloadsFolder = Cypress.config('downloadsFolder')
const mask = `${downloadsFolder}/ABC*.xlsx`
cy.task('findFiles', mask).then((foundImage) => {
expect(foundImage).to.be.a('string')
cy.log(`found image ${foundImage}`)
})
Cypress example
Assuming you are running a recent version of Cypress,
Add a task to read the downloads folder in /cypress.config.js
const { defineConfig } = require('cypress')
const fs = require('fs')
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
filesInDownload (folderName) {
return fs.readdirSync(folderName)
},
})
}
}
})
In the test
const downloadsFolder = Cypress.config('downloadsFolder')
cy.task('filesInDownload', downloadsFolder).then(files => {
const abcFile = files.find(file => file.startsWith('ABC'))
expect(abcFile).to.not.be.undefined
})
I recommend you set the downloadsFolder configuration, as this will remove files between test runs.

Cannot find module babel-preset-es2015 in cypress

The erros occurs when i add
const replace = require("replace-in-file"); in file to my code
const replace = require("replace-in-file");
const options = {
files: "./config/dashboardData.json",
configFile: true,
from: /}\n{/g,
to: ",\n",
};
I have installed babel and configured the preset still I got the issue
The package replace-in-file handles files on the OS, so it needs to be called from Node.
You would need to set up a Cypress task.
In Cypress ver 10+, do this in cypress.config.js
// cypress.config.js
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
replaceTask(options) {
const replace = require("replace-in-file");
try {
const results = replace.sync(options);
return results
}
catch (error) {
return error
}
},
})
},
// other e2e configuration here
},
});
// test.spec.cy.js
it('calls replace-in-file', () => {
const options = {
files: "./config/dashboardData.json",
configFile: true,
from: /}\n{/g,
to: ",\n",
};
cy.task('replaceTask', options).then(resultsOrError => {
console.log(resultsOrError)
})
});

CDK Lambda NodejsFunction pdfmake Types

How can I get pdfmake types working in an AWS CDK NodejsFunction Lambda?
For example, I'd like VSCode to highlight invalid properties and show intelliSense on objects.
// I'd like to type the doc definition like this:
const definition: TDocumentDefinitions = { ...
// And type the styles definition like this:
const styles: StyleDictionary = { ...
// Also, if I add styles to the docDefinition I get a type error that I have to tell typescript to ignore with #ts-ignore:
// Error: Argument of type '{ content: never[]; styles: { p: { margin: number[]; }; }; }' is not assignable to parameter of type 'TDocumentDefinitions'.
const styles = {
p: { margin: [0, 0] }
};
const docDefinition = {
content: [],
styles
}
printer.createPdfKitDocument(docDefinition)
The following pdfmake code below works but is not typed!
AWS CDK code:
new lambdaNJS.NodejsFunction(this, 'MyLambdaFunction', {
...
bundling: {
...
nodeModules: ['pdfmake'], // List of modules that should NOT be bundled but instead included in the node_modules folder.
}
});
Lambda Typescript code:
import PdfPrinter = require('pdfmake');
const fonts = {
Courier: {
normal: 'Courier',
bold: 'Courier-Bold',
italics: 'Courier-Oblique',
bolditalics: 'Courier-BoldOblique'
},
Helvetica: {
normal: 'Helvetica',
bold: 'Helvetica-Bold',
italics: 'Helvetica-Oblique',
bolditalics: 'Helvetica-BoldOblique'
},
Times: {
normal: 'Times-Roman',
bold: 'Times-Bold',
italics: 'Times-Italic',
bolditalics: 'Times-BoldItalic'
},
Symbol: {
normal: 'Symbol'
},
ZapfDingbats: {
normal: 'ZapfDingbats'
}
};
const docDefinition = {
content: [
'First paragraph'
],
defaultStyle: {
font: 'Helvetica'
}
};
const printer = new PdfPrinter(fonts);
const doc = printer.createPdfKitDocument(docDefinition);
doc.end();
My package.json contains: #types/pdfmake
There's a GitHub post here https://github.com/bpampuch/pdfmake/issues/525 where someone was able to get types working like this. But it's not clear what environment they are running or if this is in nodejs or browser.
import { StyleDictionary } from 'pdfmake/interfaces';
const styles: StyleDictionary = {
...
};
The following compiles in my VSCode but when deployed to Lambda results in a pdfmake/interfaces not found error.
import pdfmakeInterfaces = require('pdfmake/interfaces');
const definition: pdfmakeInterfaces.TDocumentDefinitions = {
...
}
The pdfmake index.d.ts file uses types and exports the main PdfPrinter object but doesn't export any types.
// Type definitions for pdfmake 0.1
// Project: http://pdfmake.org
// Definitions by: Milen Stefanov <https://github.com/m1llen1um>
// Rajab Shakirov <https://github.com/radziksh>
// Enzo Volkmann <https://github.com/evolkmann>
// Andi Pätzold <https://github.com/andipaetzold>
// Neal Mummau <https://github.com/nmummau>
// Jean-Raphaël Matte <https://github.com/jeralm>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
/// <reference types="pdfkit" />
import { BufferOptions, TDocumentDefinitions, TFontDictionary } from './interfaces';
declare class PdfPrinter {
constructor(fontDescriptors: TFontDictionary);
createPdfKitDocument(docDefinition: TDocumentDefinitions, options?: BufferOptions): PDFKit.PDFDocument;
}
export = PdfPrinter;

Read excel files in Cypress

I am new to Cypress. How to read data from excel files using Cypress? Searched in google but could not find useful answers.
In cypress you can create cypress task to read xlsx file with SheetJS library.
Usage
cypress\integration\read-xlsx.spec.js
context('Xlsx file', () => {
it('Read excel file', () => {
cy.task('readXlsx', { file: 'my-excel.xlsx', sheet: "Sheet1" }).then((rows) => {
expect(rows.length).to.equal(543)
// expect(rows[0]["column name"]).to.equal(11060)
})
})
})
Need to install xlsx
$ npm install xlsx
Create read excel fuction
cypress\plugins\read-xlsx.js
const fs = require('fs');
const XLSX = require('xlsx');
const read = ({file, sheet}) => {
const buf = fs.readFileSync(file);
const workbook = XLSX.read(buf, { type: 'buffer' });
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
return rows
}
module.exports = {
read,
}
Use function as Cypress task (plugin)
cypress\plugins\index.js
const readXlsx = require('./read-xlsx')
module.exports = (on, config) => {
on('task', {
'readXlsx': readXlsx.read
})
}
Here is an instruction how to use excel as source for cypress tests https://medium.com/#you54f/dynamically-generate-data-in-cypress-from-csv-xlsx-7805961eff55
First you need to conver your xlsx file to json with Xlsx
import { writeFileSync } from "fs";
import * as XLSX from "xlsx";
try {
const workBook = XLSX.readFile("./testData/testData.xlsx");
const jsonData = XLSX.utils.sheet_to_json(workBook.Sheets.testData);
writeFileSync(
"./cypress/fixtures/testData.json",
JSON.stringify(jsonData, null, 4),
"utf-8"
);
} catch (e) {
throw Error(e);
}
Then import json file and loop over each row and use the data in the way you want. In this example it tries to log in to a system.
import { login } from "../support/pageObjects/login.page";
const testData = require("../fixtures/testData.json");
describe("Dynamically Generated Tests", () => {
testData.forEach((testDataRow: any) => {
const data = {
username: testDataRow.username,
password: testDataRow.password
};
context(`Generating a test for ${data.username}`, () => {
it("should fail to login for the specified details", () => {
login.visit();
login.username.type(data.username);
login.password.type(`${data.password}{enter}`);
login.errorMsg.contains("Your username is invalid!");
login.logOutButton.should("not.exist");
});
});
});
});
For me the first answer pretty much worked. But i had to make a small fix.
Use function as Cypress task (plugin)
cypress/plugins/index.js
const readXlsx = require('./read-xlsx')
module.exports = (on, config) => {
on('task', {
'readXlsx': readXlsx.read
})
}
when i used this code i got the below error in cypress.
CypressError
cy.task('log') failed with the following error:
The task 'log' was not handled in the plugins file. The following tasks are registered: readXlsx
and the below fix worked
const readXlsx = require('./read-xlsx')
module.exports = (on, config) => {
on('task', {
'readXlsx': readXlsx.read,
log (message) {
console.log(message)
return null
}
})
}

Integrate jsPDF in Nativescript

I researched that using jsPDF, json response cna be converted into PDF and then can be downloaded. Is there any way to integrate JsPDF in nativescript application?
Check the following POC with jsPDF and NativeScript, you need to override some global variables required by jsPDF and install some packages from npm:
global['window'] = {
'document': {
'createElementNS': () => { return {} }
}
};
global['document'] = {
'createElement': (str) => { return {} }
};
global['navigator'] = {};
import * as base64 from 'base-64';
import * as utf8 from 'utf8';
import * as jsPDF from 'jspdf';
global['btoa'] = (str) => {
var bytes = utf8.encode(str);
return base64.encode(bytes);
};
Example: https://play.nativescript.org/?template=play-ng&id=OGrw9s&v=8
By other hand, you can use a NativeScript shim for aotb / btoa functions, to avoid install more packages from npm (Only install jspdf and #types/jspdf): https://play.nativescript.org/?template=play-ng&id=OGrw9s&v=13
As you can see in the logic of the component, you need to import the file and modify some global variables:
require('../base64')
global['window'] = {
'document': {
'createElementNS': () => { return {} }
},
'atob': global['atob']
};
global['document'] = {
'createElement': (str) => { return {} }
};
global['navigator'] = {};
It would be much better to create a fork of jsPDF with that solution.
And later you can create your PDF:
generatePDF() {
var doc = new jsPDF('p', 'pt');
doc.setFontSize(26);
doc.text(40, 50, "My first PDF with NativeScript!");
//Add image
doc.addImage(imgData, 'JPEG', 20, 90, 300, 300)
var base64 = doc.output('datauristring')
dialogs.alert({
title: "PDF - Base64",
message: base64,
okButtonText: "Copy text"
}).then(() => {
clipboard.setText(base64)
});
}

Resources