Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
how to fix await with forEach
const url = await Canvas.loadImage(getvalueof.displayAvatarURL( { format: "png", dynamic: true } ))
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
client.on('voiceStateUpdate' , (Old,New) => {
if(New.bot) return;
if(Old.bot) return;
if(New.channelId == voiceID) {
New.guild.members.cache.filter(m => m.roles.cache.get("1026253368198451270")).forEach(async sa => {
console.log("hi");
const w = ['4Skysupport.png'];
let Image = Canvas.Image,
canvas = new Canvas.createCanvas(1280, 720),
ctx = canvas.getContext('2d');
ctx.patternQuality = 'bilinear';
ctx.filter = 'bilinear';
ctx.antialias = 'subpixel';
ctx.shadowColor = 'rgba(0, 0, 0, 0.4)';
ctx.shadowOffsetY = 2;
ctx.shadowBlur = 2;
fs.readFile(`${w[Math.floor(Math.random() * w.length)]}`, function (err, Background) {
if (err) return console.log(err);
const BG = Canvas.Image;
const ground = new Image;
ground.src = Background;
let user = New.member.user;
var men = New.member.user;
var heg;
if(men) {
heg = men
} else {
heg = New.member.user;
}
var mentionned = New.member.user;
var h;
if(mentionned) {
h = mentionned
} else {
h = New.member.user;
}
var ment = New.member.user;
var getvalueof;
if(ment) {
getvalueof = New.member.user;
} else {
getvalueof = New.member.user;
}
const url = await Canvas.loadImage(getvalueof.displayAvatarURL( { format: "png", dynamic: true } ))
// Small Avatar
let Avatar = Canvas.Image;
let ava1 = new Avatar;
ava1.src = url;
ctx.beginPath();
ctx.arc(400, 400, 0, 2 * Math.PI);
ctx.drawImage(ava1, 450, 601, 80, 70);
ctx.restore();
ctx.font = '35px Arial Bold';
ctx.fontSize = '40px';
ctx.fillStyle = "#dadada";
ctx.textAlign = "center";
//background
ctx.drawImage(ground, 0, 0, 1280, 720);
var ment1 = sa.user;
var getvalueof1;
if(ment1) {
getvalueof1 = sa.user;
} else {
getvalueof1 = sa.user;
}
const url1 = await Canvas.loadImage(getvalueof1.displayAvatarURL( { format: "png", dynamic: true } ))
// Avatar
let Avatar1 = Canvas.Image;
let ava = new Avatar1;
ava.src = url1;
ctx.beginPath();
ctx.drawImage(ava, 488, 50, 260, 250);
ctx.font = '35px Arial Bold';
ctx.fontSize = '40px';
ctx.fillStyle = "#dadada";
ctx.textAlign = "center";
ctx.beginPath();
ctx.stroke();
sa.send({files: [canvas.toBuffer()]});
})
})
}
});
for await is supposed to be used with asynchronous iterators
for await (const res of items.map(e => somethingAsync(e))) …
instead of
New.guild.members.cache.filter(m => m.roles.cache.get("1026253368198451270")).forEach(async sa =>
you can use
for await (const res of New.guild.members.cache.filter(m => m.roles.cache.get("1026253368198451270"))) …
I am making an online text editor that saves the content to a database while typing and returns it to the textarea, using TinyMCE, React as frontend and Node+Express as backend
Sometimes it doesn't send the whole content to the database and i have to switch tabs and return to the editor, typing a space character so it sends the resting content
I tried using "onKeyUp", "onKeyDown" but the characters got imediatly deleted after trying to type, currently I'm using "onEditorChange" to activate the function.
Here's my code:
function App() {
const editorRef = useRef();
const { route } = useParams();
const url = "https://API/" + route;
const { httpConfig } = useFetch(url);
const [notas, setNotas] = useState("");
const [rota, setRota] = useState("");
const [init, setInit] = useState(false);
useEffect(() => {
(async () => {
let res = "";
let data = "";
if (init) {
const notinhas = {
content: notas,
rota: route,
};
httpConfig(notinhas, "PATCH");
} else {
res = await fetch(url);
data = await res.json();
if (data === null) {
const notinhas2 = {
content: "",
rota: route,
};
httpConfig(notinhas2, "POST");
} else {
setNotas(data.content);
}
}
})();
}, [notas, init]);
function onClickHandler() {
setNotas(editorRef.current.getContent());
}
return (
<div>
<Editor
onEditorChange={onClickHandler}
onInit={ (evt, editor) =>
{editorRef.current = editor;
editor.selection.select(editor.getBody(), true);
editor.selection.collapse(false);
setInit(true);
}}
init={{
plugins: "...",
toolbar: "...",
setup: function(editor) {
editor.on('keydown', function() {
var currNode = editor.selection.getNode();
var currText = currNode.textContent;
if (currNode.nodeName.toLowerCase() != 'p' || currText.length < 1) return;
var pCount = editor.dom.doc.querySelectorAll('p').length;
setTimeout(function() {
var newNode = editor.selection.getNode();
var newText = newNode.textContent;
var newPCount = editor.dom.doc.querySelectorAll('p').length;
if (pCount + 1 == newPCount && currText == newText) {
var nextNode = newNode.nextElementSibling;
var nextNodeText = nextNode.textContent;
if (nextNode.nodeName.toLowerCase() != 'p' || nextNodeText.length > 1) return;
nextNode.innerHtml = '<br>';
editor.selection.setCursorLocation(nextNode, 0);
}
}, 80);
});
editor.on('init', function()
{
this.getDoc().body.style.fontSize = '12pt';
this.getDoc().body.style.fontFamily = 'monospace';
});
}}}
value={notas}
/>
</div>
);
}
export default App;
Could someone help me in this?
I have two Temp. Sensors on my Raspberry Pi and I have a node.js Express app. I want to create nedb databases dynamically of an array with sensor objects.
So I have an object with sensors in it:
sensors: [
{
name: "Indoor",
type: 22,
pin: 21
},
{
name: "Outdoor",
type: 22,
pin: 21
}
]};
Now I want to create for every Sensor three database:
databaseSetup(app.sensors);
function databaseSetup(sensor){
const dataStore = require('nedb');
const databaseVariables = [];
sensor.forEach((sensor) => {
const live = 'live' + sensor.name;
const seconds = 'seconds' + sensor.name;
const hours = 'hours' + sensor.name;
const test = {
live: new dataStore(`./databases/temp/${sensor.name}/live.db`),
seconds: new dataStore(`./databases/temp/${sensor.name}/seconds.db`),
hours: new dataStore(`./databases/temp/${sensor.name}/hours.db`) }
databaseVariables.push(test);
});
}
But this is not working. Can someone help me please?
I am not sure why you trying to do cause in my mind this is a bad practice. but you can make it dynamic. something like this:
const dt = require('nedb');
const db = [];
//USING LOOP and FUNCTION
let list = [{ name: "GasSensor" }, { name: "TempSensor" }];
let index = 0;
//BAD Practice
let setup = () => {
if (index + 1 > list.length) return;
let newInstance = new dt({ filename: 'nodejs/data/nedb_' + list[index].name, autoload: true });
console.log("Working on index " + (index + 1));
newInstance.loadDatabase((err) => {
if (err) {
//...
} else {
db.push(newInstance);
}
index++;
setup();
});
}
setup();
And also with API:
const exp = require("express");
const app = exp();
const dt = require('nedb');
const db = [];
app.get("/make/db/:name", (q, r) => {
//BAD PRACTICE
//JUST FOR TEST
let newInstance = new dt({ filename: 'nodejs/data/nedb_' + q.params.name, autoload: true });
newInstance.loadDatabase((err) => {
if (err) {
console.log(err + "");
r.send("ERROR");
}
else {
db.push(newInstance);
console.log("Database is loaded");
r.send("NEW DB CREATED");
}
});
});
app.listen(3000);
I'm trying to add AnalyserNode and visualize the output sound to a web audio example that I made but I can't figure out how. I think I am not passing the right source to the analyser (?)
Here for the full code : https://jsfiddle.net/kepin95043/1ub0sjo3/
<script>
var fs = 2000;
var gain = 0.2;
class Sound {
constructor(context) {
this.context = context;
}
init() {
this.oscillator = this.context.createOscillator();
this.oscillator.frequency.value = fs;
this.gainNode = this.context.createGain();
this.oscillator.connect(this.gainNode);
this.gainNode.connect(this.context.destination);
}
play(value) {
this.init();
this.gainNode.gain.setValueAtTime(gain, this.context.currentTime);
this.oscillator.start();
}
stop() {
this.gainNode.gain.exponentialRampToValueAtTime(0.001, this.context.currentTime + 1);
this.oscillator.stop(this.context.currentTime + 1);
}
}
var context = new AudioContext();
var sound = new Sound(context);
sound.init();
var wave = 'sine';
var state = 'paused';
var waveSelectors = document.querySelectorAll('.waveform');
var playBtn = document.querySelector('#play');
var container = document.querySelector('.container');
waveSelectors.forEach(function(button) {
button.addEventListener('click', function() {
cleanClass('active');
wave = button.dataset.wave;
sound.oscillator.type = wave;
button.classList.add('active');
})
})
playBtn.addEventListener('click', function() {
context.resume().then(() => {
console.log('Playback resumed successfully');
});
if (playBtn.text == 'Play') {
sound.play();
sound.oscillator.type = wave;
playBtn.text = 'Pause';
} else {
sound.stop();
playBtn.text = 'Play';
}
})
function cleanClass(rclass) {
waveSelectors.forEach(function(button) {
button.classList.remove(rclass);
})
}
function changeFs(val) {
fs = val;
var output = document.getElementById("fsValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
function changeGain(val) {
gain = val;
var output = document.getElementById("gainValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
var masterGain;
masterGain = context.createGain();
masterGain.connect(context.destination);
// analyser
var analyser = context.createAnalyser();
masterGain.connect(analyser);
var waveform = new Float32Array(analyser.frequencyBinCount);
analyser.getFloatTimeDomainData(waveform);
(function updateWaveform() {
requestAnimationFrame(updateWaveform);
analyser.getFloatTimeDomainData(waveform);
}());
var spectrum = new Uint8Array(analyser.frequencyBinCount);
(function updateSpectrum() {
requestAnimationFrame(updateSpectrum);
analyser.getByteFrequencyData(spectrum);
}());
// oscilloscope
var scopeCanvas = document.getElementById('canvas');
scopeCanvas.width = waveform.length;
//scopeCanvas.height = 200;
scopeCanvas.height = scopeCanvas.width * 0.33;
var scopeContext = scopeCanvas.getContext('2d');
(function drawOscilloscope() {
requestAnimationFrame(drawOscilloscope);
scopeContext.clearRect(0, 0, scopeCanvas.width, scopeCanvas.height);
scopeContext.strokeStyle="white"; // Green path
scopeContext.beginPath();
for (var i = 0; i < waveform.length; i++) {
var x = i;
var y = (0.5 + waveform[i] / 2) * scopeCanvas.height;
if (i === 0) {
scopeContext.moveTo(x, y);
} else {
scopeContext.lineTo(x, y);
}
}
scopeContext.stroke();
}());
</script>
Could anyone help me to identify what I'm doing wrong?
Thank in advance!
PS: Open it with Firefox. Does not work on Chromium based browsers for me.
Here is a working example: https://codepen.io/dennisgaebel/pen/YEwLaL
You create a Sound object and also a masterGain that is connected to your AnalyserNode. But I don't see where the sound ever connects to the masterGain. Without that, your analyser node just gets silence.
Here is the full working script code:
var fs = 2000;
var gain = 0.2;
class Sound {
constructor(context) {
this.context = context;
}
init() {
this.oscillator = this.context.createOscillator();
this.oscillator.frequency.value = fs;
this.gainNode = this.context.createGain();
this.oscillator.connect(this.gainNode);
this.gainNode.connect(this.context.destination);
}
play(value) {
this.init();
this.gainNode.gain.setValueAtTime(gain, this.context.currentTime);
this.oscillator.start();
// connect analyser to the gainedSource
this.gainNode.connect(analyser);
// for the non gainedSource
//this.gainNode.connect(analyser);
}
stop() {
this.gainNode.gain.exponentialRampToValueAtTime(0.001, this.context.currentTime + 1);
this.oscillator.stop(this.context.currentTime + 1);
}
}
var context = new AudioContext();
var sound = new Sound(context);
sound.init();
var wave = 'sine';
var state = 'paused';
var waveSelectors = document.querySelectorAll('.waveform');
var playBtn = document.querySelector('#play');
var container = document.querySelector('.container');
waveSelectors.forEach(function(button) {
button.addEventListener('click', function() {
cleanClass('active');
wave = button.dataset.wave;
sound.oscillator.type = wave;
button.classList.add('active');
})
})
playBtn.addEventListener('click', function() {
context.resume().then(() => {
console.log('Playback resumed successfully');
});
if (playBtn.text == 'Play') {
sound.play();
sound.oscillator.type = wave;
playBtn.text = 'Pause';
} else {
sound.stop();
playBtn.text = 'Play';
}
})
function cleanClass(rclass) {
waveSelectors.forEach(function(button) {
button.classList.remove(rclass);
})
}
function changeFs(val) {
fs = val;
var output = document.getElementById("fsValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
function changeGain(val) {
gain = val;
var output = document.getElementById("gainValue");
output.innerHTML = val;
sound.stop();
sound.play();
console.log(val);
};
// analyser node
var analyser = context.createAnalyser();
var waveform = new Float32Array(analyser.frequencyBinCount);
analyser.getFloatTimeDomainData(waveform);
(function updateWaveform() {
requestAnimationFrame(updateWaveform);
analyser.getFloatTimeDomainData(waveform);
}());
var spectrum = new Uint8Array(analyser.frequencyBinCount);
(function updateSpectrum() {
requestAnimationFrame(updateSpectrum);
analyser.getByteFrequencyData(spectrum);
}());
// oscilloscope
var scopeCanvas = document.getElementById('canvas');
scopeCanvas.width = waveform.length;
scopeCanvas.height = scopeCanvas.width * 0.33;
var scopeContext = scopeCanvas.getContext('2d');
(function drawOscilloscope() {
requestAnimationFrame(drawOscilloscope);
scopeContext.clearRect(0, 0, scopeCanvas.width, scopeCanvas.height);
scopeContext.strokeStyle = "white"; // Green path
scopeContext.beginPath();
for (var i = 0; i < waveform.length; i++) {
var x = i;
var y = (0.5 + waveform[i] / 2) * scopeCanvas.height;
if (i === 0) {
scopeContext.moveTo(x, y);
} else {
scopeContext.lineTo(x, y);
}
}
scopeContext.stroke();
}());
I created a very simple cube using Blender and exported it using the Three.js Blender Exporter.
I am now attempting to load the exported model and apply a texture using Node. When I run the script, I see no error. What am I doing wrong?
'use strict';
const JSDOM = require('jsdom').JSDOM;
const THREE = require('three');
const dom = new JSDOM(`<!DOCTYPE html><html><head></head><body></body></html>`);
global.window = dom.window;
global.document = dom.window.document;
global.XMLHttpRequest = require('xhr2');
const loadTexture = (path) => {
return new Promise((resolve, reject) => {
const loader = new THREE.TextureLoader();
loader.load(
path,
// success
(texture) => resolve(texture),
// progress
undefined,
// error
(error) => reject(error)
);
});
};
const loadGeometry = (path) => {
const loader = new THREE.JSONLoader();
return new Promise((resolve, reject) => {
loader.load(
path,
// success
(geometry) => resolve(geometry),
// progress
undefined,
// error
(error) => reject(error)
);
});
};
const createObject = () => {
return Promise.all([
loadTexture('./image.jpg'),
loadGeometry('./cube.json')
]).then(results => {
const texture = results[0];
const material = new THREE.MeshBasicMaterial({map: texture});
const geometry = results[1];
const object = new THREE.Mesh(geometry, material);
return object;
});
};
const scene = new THREE.Scene();
createObject()
.then(object => {
scene.add(object);
console.log('Success!');
})
.catch(error => console.error(error.message));
Here is the model I am using:
{
"normals":[-5.32907e-15,-1,2.98023e-08,1.06581e-14,1,-2.98023e-08,1,4.47034e-08,2.83122e-07,-2.83122e-07,-7.45059e-08,1,-1,-1.3411e-07,-2.23517e-07,2.38419e-07,1.78814e-07,-1],
"faces":[33,0,1,2,3,0,0,0,0,33,4,7,6,5,1,1,1,1,33,0,4,5,1,2,2,2,2,33,1,5,6,2,3,3,3,3,33,2,6,7,3,4,4,4,4,33,4,0,3,7,5,5,5,5],
"metadata":{
"normals":6,
"faces":6,
"type":"Geometry",
"vertices":8,
"generator":"io_three",
"uvs":0,
"version":3
},
"vertices":[1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1,0.999999,1,1,-1,1,1,-1,1,-1],
"uvs":[]
}
Well, I got something almost working:
'use strict';
const fs = require('fs');
const JSDOM = require('jsdom').JSDOM;
const THREE = global.THREE = require('three');
require('three/examples/js/renderers/Projector');
const CanvasRenderer = require('three/examples/js/renderers/CanvasRenderer');
const Canvas = require('canvas');
const dom = new JSDOM(`<!DOCTYPE html><html><head></head><body></body></html>`);
global.window = dom.window;
global.document = dom.window.document;
global.XMLHttpRequest = require('xhr2');
const loadTexture = (url) => {
const loader = new THREE.FileLoader();
return new Promise((resolve, reject) => {
console.log('loading texture');
loader.load(
url,
// success
(texture) => {
console.log('loaded texture');
resolve(texture);
},
// progress
undefined,
// error
(error) => {
console.log('error loading texture');
reject(error);
}
);
});
};
const loadGeometry = (url) => {
const loader = new THREE.JSONLoader();
return new Promise((resolve, reject) => {
console.log('loading geometry');
loader.load(
url,
// success
(geometry) => {
console.log('loaded geometry');
resolve(geometry);
},
// progress
undefined,
// error
(error) => {
console.log('error loading geometry');
reject(error);
}
);
});
};
const createObject = () => {
return Promise.all([
loadTexture('http://localhost:8000/image.jpg'),
loadGeometry('http://localhost:8000/cube.json')
]).then(results => {
const texture = results[0];
const geometry = results[1];
const material = new THREE.MeshBasicMaterial({map: texture});
const object = new THREE.Mesh(geometry, material);
return object;
});
};
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const canvas = new Canvas(800, 800);
const renderer = new THREE.CanvasRenderer({
canvas: canvas
});
camera.position.z = 5;
canvas.style = {};
renderer.setClearColor(0xffffff, 0);
renderer.setSize(800, 800);
createObject()
.then(object => {
scene.add(object);
renderer.render(scene, camera);
const out = fs.createWriteStream('./rendered.png');
const canvasStream = canvas.pngStream();
canvasStream.on('data', function (chunk) { out.write(chunk); });
canvasStream.on('end', function () { console.log('done'); });
})
.catch(error => console.error(error.message));
Except it renders a blank, transparent PNG.