generating spectrogram form wav file nodejs and save it - javascript

i'm new in the world of javascript and i wanted to recreate a project of mine (written in python) with javascript.
so i want to write a script with nodejs that reads a wav file and generate from it a spectrogram.
I used node-wav , canvas and audio-context trying to recreate the method applied in this module
I'm working with local files from my laptop and with javascript client side. I want to do everything locally. This is my code :
const canvas = createCanvas(480, 240)
const spectro = spectrogram(canvas, false)
const spectrogramsGenerator = async () => {
// wavfiles return a list of wav files (it works)
const files = await wavFiles()
for (file in files) {
const buffer = fs.readFileSync('path/to/file/' + files[file])
spectro.connectSource(buffer, audioContext)
spectro.start()
}
}
with that code snippet i get the following error :
/path/to/workspace/node_modules/spectrogram/spectrogram.js:34
window.onresize = function() {
^
ReferenceError: window is not defined
at new Spectrogram (/path/to/workspace/spectrogram/spectrogram.js:34:5)
at Spectrogram (/path/to/workspace/node_modules/spectrogram/spectrogram.js:16:14)
at Object.<anonymous> (/path/to/workspace/spectrogram.js:13:17)
at Module._compile (internal/modules/cjs/loader.js:736:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
at Module.load (internal/modules/cjs/loader.js:628:32)
at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
at Function.Module._load (internal/modules/cjs/loader.js:560:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
at executeUserCode (internal/bootstrap/node.js:526:15)
if this the wrong way doing it (i think it is) .. what packages should i use to achieve my goal or how should i approach this problem. Thanks in advance

Related

JS Script using DOM running on pm2 server

I have read that serverside, you cant use DOM. I've created a web application using DOM and I wonder what needs to be done to reproduce this code to make it work on a server, so the people on the internet can work with it. Here is a little peak of a code:
// Listen for export button click
document.getElementById('exportForm').addEventListener('submit', function (e) {
setTimeout(exportData, 20);
e.preventDefault();
});
// Export data function
function exportData(e) {
console.log("Exporting...");
// device details and time range details
const devId = (document.getElementById('deviceInput')).value;
var dateFrom = (document.getElementById('dateFromInput')).value;
var dateTo = (document.getElementById('dateToInput')).value;
var timeFrom = (document.getElementById('timeFromInput')).value;
var timeTo = (document.getElementById('timeToInput')).value;
const limit = (document.getElementById('limitInput')).value;
const key = (document.getElementById('keysInput')).value;
When I try to run it on server using pm2 start app.js, it returns this error:
ReferenceError: document is not defined
at Object.<anonymous> (/home/cloud/sites/App/app.js:6:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/ProcessContainerFork.js:33:23)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
I've heard about JSDom, but I think there needs to be html included in a string and then I have no idea how to connect the css in there and so on. Is there a better way for me to make this work?
Document object is a browser feature hence you cant use it inside server, Instead you have other features like the FS (File System)
Anyhow using JSDom may be possible, you have to rewrite using inline styles https://www.codecademy.com/article/html-inline-styles which is not a good practice and you should avoid it

Discord Bot initialization Failure

I have a problem in creating the main file for my discord bot. currently, i encountered a problem in trying to get my bot to work but sadly, this error message has been outputted from the console.
PS C:\Users\Kelvin Wang\Documents\Projects\DiscordBot> node index.js
node:internal/modules/cjs/loader:1170
throw err;
^
SyntaxError: C:\Users\Kelvin Wang\Documents\Projects\DiscordBot\config.json: Unexpected end of JSON input
at parse (<anonymous>)
at Object.Module._extensions..json (node:internal/modules/cjs/loader:1167:22)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\Users\Kelvin Wang\Documents\Projects\DiscordBot\index.js:4:19)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
My code in index.js is this:
//initial discord initialization of client and library
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const dotenv = require('dotenv');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ferraribot is online!');
});
// Login to Discord with your client's token
client.login(token);
While my config.json looks like this:
{
"token": "token"
}
Any help would be much appreciated! This is my first time using stack overflow so I'm sorry for any wrong formatting that I've done. Thanks in advance!
Your code looks just fine.
The error said, your code has some problems reading the JSON config. (is it in the same directory?)
First try your code using your token in the index.js. client.login(*****) // just don't upload e.g. github ;)
Second, I believe better practice using .env for sensitive information. https://www.npmjs.com/package/dotenv

TypeError: jQuery.getJSON is not a function [duplicate]

I'm new to Node.js. I already have a frontend javascript script that uses an API and gets weather data like so:
function getTextWeatherUsingStation(theStation){
theURL = 'https://api.weather.gov/stations/' + theStation + '/observations/current';
// return new Promise((resolve, reject) => {
$.getJSON(theURL,function(data){
var myJSON = JSON.stringify(data)
I read that you can't just use a library as is. I converted it over to a Node.js friendly file by wrapping it in
module.exports = {
and altering the function to:
getTextWeatherUsingStation: function(theStation){
It was having problem with promise so I just commented it out as you can see.
I was getting errors on the $.getJSON line and figured it was because I hadn't included jQuery so I used npm to install that.
I'm still getting this and can't figure out why:
....\drupal-8.4.5\stationFunctionsNode.js:34
$.getJSON(theURL,function(data){
^
ReferenceError: $ is not defined
at Object.getTextWeatherUsingStation (C:\Users\edwin.brown\Sites\devdesktop\drupal-8.4.5\stationFunctionsNode.js:34:13)
at Object.<anonymous> (C:\Users\edwin.brown\Sites\devdesktop\drupal-8.4.5\nodeTestWData.js:8:18)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
$.getJSON is jQuery's function for front to make http requests.
You are on backend now. So things will be little different here. This is not how you make requests from backend instead should consider using one of the native modules to make http requests which is http module and you use it like
http.request(Options, function(res) { ...
Or if you want to use something like getJson here is get-json library that you can use like
getJSON('URL', function(error, response){..
Ofcourse you'll have to install it first with npm install get-json
then use in your project like var getJSON = require('get-json')

Undefined variable, nodejs, json to program variable

I decided to save data the dirty way to a .json file. For some reason, when I run my index.js file which runs other modules I have written, it says that a particular variable I initialized in a separate module is undefined (one I was hoping to reference from json). The structure of my program is the standard index file that loads functions from modules I have written and executes them via endpoints.
.json File
{"blocks":[{"GENESIS_DATA":{"timestamp":1,"lastHash":"v01d","hash":"?M=(((Position-1)=>ter)=>sen)=>non?","difficulty":20,"nonce":0,"data":[]}}]}
I want to take the first index of this array named GENESIS_DATA and use it as an array in my program...
relevant code from blockchain index (not the file I execute for the program to run)
const { REWARD_INPUT, MINING_REWARD, GENESIS_DATA } = require('../config');
const fs = require('fs');
const jsonRoute = '/home/main/public_html/Cypher-Network/CDSM/CDSM.json';
class Blockchain {
constructor() {
fs.readFile(jsonRoute, 'utf-8', function(err, data) {
if (err) throw err;
this.jsonChain = JSON.parse(data);
const genesis = jsonChain.blocks[0];
});
this.chain = [genesis];
}
/*Alot more code down here but let's assume that the bracket for class Blockchain is completed*/
}
error log
/home/main/public_html/Cypher-Network/blockchain/index.js:32
this.chain = [genesis]; //we are taking the first element of the json file (genesis block)
^
ReferenceError: genesis is not defined
at new Blockchain (/home/main/public_html/Cypher-Network/blockchain/index.js:32:19)
at Object.<anonymous> (/home/main/public_html/Cypher-Network/index.js:28:20)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
main#goldengates.club [~/public_html/Cypher-Network]#
First, the constant genesis is local to the callback, so it is getting destroyed just after the callback has finished running.
Also even if the constant was declared outside the callback, remember that fs.readFile is asynchronous, so while readFile is reading the file containing the data, the constant genesis will have already been set to undefined.

How to manage multiple .js files so as to run automated test cases using their tags in CucumberJS?

I am using CucumberJS with Selenium-Webdriver for automating my test cases. Currently I am having multiple feature files with their respective step-definition files. When I am trying to run the test cases then it is throwing an error:
Error: The previously configured ChromeDriver service is still
running. You must shut it down before you may adjust its
configuration.
at Object.setDefaultService (D:\code\egov-test-cases\node_modules\selenium-webdriver\chrome.js:305:11)
at new World (D:\code\egov-test-cases\features\support\world.js:21:12)
at Object. (D:\code\egov-test-cases\features\steps\create_approver_remittance_master.js:15:13)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at supportCodePaths.forEach.codePath (D:\code\egov-test-cases\node_modules\cucumber\lib\cli\index.js:142:42)
at Array.forEach ()
at Cli.getSupportCodeLibrary (D:\code\egov-test-cases\node_modules\cucumber\lib\cli\index.js:142:22)
at D:\code\egov-test-cases\node_modules\cucumber\lib\cli\index.js:169:41
at Generator.next ()
at asyncGeneratorStep (D:\code\egov-test-cases\node_modules\cucumber\lib\cli\index.js:44:103)
error Command failed with exit code 1. info Visit
https://yarnpkg.com/en/docs/cli/run for documentation about this
command.
Since I am automating the tests, I have put the below code for automating chrome in world.js file, and then tried importing the driver from world.js, but still it is giving the same error.
class World {
constructor() {
const { setDefaultTimeout } = require('cucumber');
const webdriver = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const path = require('chromedriver').path;
const screen = {
width: 640,
height: 480
};
setDefaultTimeout(100 * 5000);
var service = new chrome.ServiceBuilder(path).build();
chrome.setDefaultService(service);
this.driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
}
}
What you may need to do is kill your browser after each test run as the containers are reused(hence why a browser may already be running). To do this you will want to add a hooks file to your support folder and include something as follows
After({}, async function(scenario) {
this.driver.quit();
}
});
for more info take a look at the docs https://github.com/cucumber/cucumber-js/blob/master/docs/support_files/hooks.md
I found the solution to my problem. Actually the driver was getting initialized multiple times and that is why it was giving me the above error. I was creating the driver inside the constructor in the class World in world.js file. Everytime i was taking an instance of the class World, I was creating a new driver. I shifted the driver declaration outside the class as const driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build() and created a method as initialize() { return driver; } in world.js file. I am calling the initialize() method in my step definition files as let world = new World(); let driver = world.initialize(). Now I am good to go!

Categories

Resources