JavaScript

2008 readers
10 users here now

founded 1 year ago
MODERATORS
101
102
 
 

async MediaUpload(photos : any[]) { const client = await this.Login() const full_photo_urls : string[] = photos.map((item) => item.full) let image_ids : string[] = []; full_photo_urls.forEach(async (image_url) => { const image_blob = await fetch(image_url).then(res => res.blob()) try { console.log("images are about to be posted!"); const image_res = await client.postMediaAttachment({file: image_blob}) console.log("Images were posted here"); console.log(image_res); } catch (error) { console.error(error); } }) return image_ids;

Runs Error block which results in this

{ failed: true, json: { id: '111037763715692057', type: 'image', url: 'https://files.botsin.space/media_attachments/files/111/037/763/715/692/057/original/c46fd6ce6b892c66.jpeg', preview_url: 'https://files.botsin.space/media_attachments/files/111/037/763/715/692/057/small/c46fd6ce6b892c66.jpeg', remote_url: null, preview_remote_url: null, text_url: null, meta: { original: [Object], small: [Object] }, description: null, blurhash: 'UEHo8yIm%gV?9Exv%fM{?u~qM_D%xvITM{xa' }, path: 'media', response: Response { [Symbol(realm)]: null, [Symbol(state)]: { aborted: false, rangeRequested: false, timingAllowPassed: true, requestIncludesCredentials: true, type: 'default', status: 200, timingInfo: [Object], cacheState: '', statusText: 'OK', headersList: [HeadersList], urlList: [Array], body: [Object] }, [Symbol(headers)]: HeadersList { cookies: null, [Symbol(headers map)]: [Map], [Symbol(headers map sorted)]: null } }, status: 200, rateLimit: 30 }

I am really confused given it gives me a status code 200 which means OK, but still says it failed??? I also used my debugging to understand this is the line where the error occurs

const image_res = await client.postMediaAttachment({file: image_blob})

also ignore the fact imageres is unused, I removed the code after it for testing since to ensure nothing else was causing the error

103
104
105
106
 
 

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/sky/Documents/hourlypets/node_modules/tsl-mastodon-api/lib/index.js from /home/sky/Documents/hourlypets/src/mastodon.ts not supported. Instead change the require of index.js in /home/sky/Documents/hourlypets/src/mastodon.ts to a dynamic import() which is available in all CommonJS modules. at require.extensions. [as .js] (/usr/lib/node_modules/ts-node/dist/index.js:851:20) at Object. (/home/sky/Documents/hourlypets/src/mastodon.ts:36:31) at m._compile (/usr/lib/node_modules/ts-node/dist/index.js:857:29) at require.extensions. [as .ts] (/usr/lib/node_modules/ts-node/dist/index.js:859:16) at Object. (/home/sky/Documents/hourlypets/src/bot.ts:13:20) at m._compile (/usr/lib/node_modules/ts-node/dist/index.js:857:29) at require.extensions. [as .ts] (/usr/lib/node_modules/ts-node/dist/index.js:859:16) at phase4 (/usr/lib/node_modules/ts-node/dist/bin.js:466:20) at bootstrap (/usr/lib/node_modules/ts-node/dist/bin.js:54:12) at main (/usr/lib/node_modules/ts-node/dist/bin.js:33:12) at Object. (/usr/lib/node_modules/ts-node/dist/bin.js:579:5) { code: 'ERR_REQUIRE_ESM' } I am importing the lib like this

import * as Mastodon from 'tsl-mastodon-api';

107
9
submitted 1 year ago* (last edited 1 year ago) by pastelmind to c/javascript
 
 

The Rome project appears to be dead. Several of its maintainers have stepped up to create a fork named Biome.

See also: tweet by Jonny Burger

108
109
3
submitted 1 year ago by philnash to c/javascript
110
111
112
 
 

Hello Everyone,

The issue: I have created a page that loads two other pages into div's at the press of a button, and then removes them on another press

Both these pages contain JavaScript. On one of the pages, the JavaScript fires when the page is loaded to fill out values pulled from a database.

The pages are loaded using a simple Ajax call, that puts the contents in the div.

The problem: obviously loading pages this way means I can't use 'document.load' to fire the JavaScript. I'm also finding that none of the scripts are loaded either.

I have a solution that can load the JavaScript after completion of the document.load, but for some reason it's not detecting the global variables with the initial Json data in it.

Both pages work individually.

The question:

  1. How do I get this to work?
  2. Is there a better (preferably non-iframe) way of doing this?
  3. Why, when the JavaScript is loaded manually, is it seeing the global Json values as 'not yet defined'?

Happy to offer any other information needed.

Thanks in advance

113
 
 

How does one fetch some JSON data and save it into a variable and not continue executing the rest of the script until the fetch api has fetch the JSON data?

Here is my code which will return undefined in the console.

var myVar;

fetch("myFile.json")
	.then(res => res.json())
	.then(data => {
	myVar = data;
});
	
console.log(myVar)

//rest of code executes...
114
115
116
 
 
117
 
 

Hi, I need to create a infinite (but breakable) cycle where I can slow down the cycle by awaiting promises inside. While cycle should be able to do this, but as you can see in the image, the duration is all over the place.

Why is this happening? Is there a way to make it close to the original sleep duration?

118
 
 

Absolute JS newbie here. I am able to use fetch() to get JSON from a URL but I can't figure out how to do anything with that JSON outside of the fetch itself.

Here's my code (API key and GPS redacted):

fetch('https://www.airnowapi.org/aq/forecast/latLong/?format=application/json&latitude=X&longitude=X&distance=50&API_KEY=X')
        .then(result => result.json())
        .then((out2) => {     
            console.log('Fetch Output: ', out2);
        }).catch(err => console.error(err)); 

Any code that references out2 other than console.log() call gives an error that out2 is undefined. How do I get access to out2 anywhere else?

119
 
 

I’ve figured out how to write libraries in Deno, and publish them to node using the DNT package, but this only works if there package is authored in Deno. I have several libraries that are already written in Node and I’d like to publish Deno packages for them, but I’m unsure how to handle the dependencies. Using the DNT tool, you effectively map the Deno dependencies to Node. How can I go the other direction and map Node dependencies to Deno so I can publish tools (like @jmondi/oauth2-server) to Deno? Here is an example going from Deno to Node: @jmondi/browser-storage

120
 
 

Thought this was a really interesting approach. I know I definitely need to consider generators for certain tasks, I currently use loops or map/forEach constructs. Also learned about for async loops today

121
 
 

Node.js version 20 comes with a new, built-in, stable test runner. This post takes a look into what you can do with it, with a small example test project.

122
 
 

I've been working on a way of analysing a page of text stored in image format (a PNG file) to try and break the text up into normal text, separated text, mathematical equations and things that are just diagrams. I post it here so that hopefully I might get some feedback.

I posted this previously in Reddit but it didn't get a lot of traction or start much of a discussion. I am hoping I might here.

I am by no means an expert in Javascript. My language of choice has been in Python but there was no good way of getting visual feedback quickly and easily as to how well my algorithm was working.

At the moment the whole thing is experimental and more of a proof of concept. In the future I am hoping it will be able to analyse uploaded PDFs and convert them to a combination of paragraph text (possibly using something like Tesseract) and for the mathematical equations to AsciiMath or Latex using something like MathPix. Then I would be able to pass it into some kind of text to speech engine.

I am still at the preliminary stages but a working demo is on https://jsdemo.kiwiheretic.xyz/

Source code is accessible from there but is also on https://github.com/kiwiheretic/textextract

Someone, after viewing an earlier version of my project, suggested that Tesseract should already do this. However, as far as I can tell, Tesseract only gives the location of decipherable text on the page and not things like diagrams.

It was written initially in Python but I converted it to Javascript because it was far easier to debug visually with Chrome developer tools. As a side benefit it also seems to run much faster. It's not particularly optimised so I am sure it could even go much faster.

The process of boxing the characters and rows of text but is probably grossly inefficient but the basic idea is as follows:

Pixel data is converted into horizontal line segments by the data_to_raster function. The line segments being stored in an array of the format [y, [x1, x2], [x3, x4]. [x5,x6].... ] where y is the height offset of that particular image pixel row and data like [x1,x2] says that all the pixels from x1 to x2 are coloured in.

Then find_boxes attempts to reread that array and turn it into boxes containing individual characters. It returns an array of arrays where the inner array takes the form [x1, y1, x2, y2] which describe the bounding box for the character inside. I initially thought it should try and find glyphs (character shapes) by working out how the individual dots were connected to make up a character. However this doesn't apply for the small letter "i" which contains a small dot at the top, for example. Therefore what I opted for in the head is that that a given character is anything that overlaps with its horizontal space. This does render the occasional false positives (like on the first line of the demo where "Ch" are wrongly guessed as one character) but doesn't seem to cause any real problems.

The get_row_sorted function, which is rather badly named, is to sort the boxes of the characters in the array to the order that they would appear in the page from left to right.

The group_into_paragraphs function attempts to divide the rows into paragraphs by computing the quartile of the row spacing and then using that to determine if the previous row belongs to the same paragraph as the next row.

The stepBoxes.step function is then used to pull all the characters out of a two dimensional array (called rowData) where the major index refers to which "line" the characters are onand the minor index is the position of that character on the line. Then I try to do some crude statistical analysis on the median and upper quartile spacing on the spacing between characters in order to further break up a row into independent segments. (You can see this in the demo on the first line and also with many of the lines containing mathematical equations.) This method is pretty crude and there is probably a better way of doing this. This whole function runs on a timer callback for the purpose of running it slower to make it easier to see what is happening in practice.

Plans for the future include a Node JS backend and the ability to load PDFs and have it produce a new PDF with image of text replaced by actual OCR'd text.

This code is by no means work of art. It needs to be refactored. I am just not 100% sure yet where that refactoring should occur. Certainly it could be made more Dry. The code could contain Javascript generators instead of loops in some places. However I think there are also places where it is unavoidable to run through an array or list twice. For instance in computing the median spacing between characters which also requires a sort. I probably also need to do the same thing for the text rows in order to identify where the paragraphs are.

Even at this stage I am happy for anyone to point me to a library or web application that already does this. Especially if it can convert the mathematical equations into text as well. (I just don't know of any.)

Anyway, constructive criticism and advice are welcomed.

Thanks

123
4
submitted 1 year ago* (last edited 1 year ago) by castarco to c/javascript
 
 

Some random ideas on NPM update policies

I'll start saying that what follows is the kind of stuff that I'm always a bit afraid to share because I mostly expect indifference or criticism, but I guess that there's no point on writing about it if it's not shared afterwards.

For a few weeks I've been thinking that, while semantic versioning is awesome, in some situations is not enough. Not everyone follows it, people break the convention accidentally, and we lack tools to manage the complexity that arises from it.

So I wrote a draft of a proposal that intends to surface some of the hidden complexity behind dependencies management to make it easier to tame, with the hope that it can help to reduce problems due to dependencies' breaking changes.

If you are interested in JavaScript or NodeJS development, I'd love to have some input from you (this also includes the criticism I always fear, as long as it's constructive 🤓)

124
 
 

cross-posted from: https://programming.dev/post/302850

Hello, everyone 👋. I am a newcomer when it comes to JavaScript. I come from an OOP background (C# and Java). I've recently learned that ES6 has a class keyword that preforms similarly (but not exactly) to common OOP languages. Normally I would be inclined to use this feature in my projects; however, it came to my attention that the usage of class in JavaScript seems to be heavily discussed (mostly in a negative light). My questions to this community are:

  • Should it be used often, sparingly, or be outright avoided?
  • What are its advantages and disadvantages?
  • Are there specific cases where the usage of class excels?

Please share your thoughts.

125
 
 

Am I the only one that feels kinda lost trying to debug things in Redux?

Maybe I got spoiled with Nuxt, maybe I need different browser tools, maybe I need to take a redux/reselect course to remind myself wtf is going on over here...

but I feel like even simple things like seeing a components props or the app state is difficult to do in browser inspector, even with the usual react browser extension.

I don't know what I'm hoping for here ... maybe a youtube video recommendation or a browser extension or a tiny violin. Either way this seemed like the best community on Lemmy to ask.

view more: ‹ prev next ›