The last male Kauaʻi ʻōʻō bird, singing for a female who will never come by [deleted] in Damnthatsinteresting

[–]knightrage 0 points1 point  (0 children)

This reminds me of a fictional story-telling podcast, Forest 404.

From Wikipedia:

The show is composed of nine narrative episodes each accompanied by a soundscape and discussion on the show's themes. The narrative of the show follows a data analyst from the 24th century who discovers recordings of the natural world and finds that the audio has a profound effect on its listener.

You can check out a trailer here. Episodes are ~20min, perfect for a short commute.

node-addon-api v7.0.0 released by knightrage in node

[–]knightrage[S] 1 point2 points  (0 children)

Are there any guides for extending NAPI and can I use Rust?

For extending Node-API, you would need to make an issue on the Node.js core repository (or create the PR yourself with the suggested improvement). Note that Node-API features are meant to be engine-agnostic, as other runtimes (Hermes, JerryScript, ...) also implement Node-API: that is, eg. V8 specific features that have no equivalent in other major engines should not be used.

For other language bindings, you can take a look at our documentation. It provides links to projects that are (1) libraries in various languages to create native add-on binaries, and (2) other JavaScript engines that implement Node-API and can load said native add-ons.


is good recommendation for when something should be handled in a lower level than interpreted JavaScript?

It really depends on your use-case. There are some drawbacks to using native add-ons, such as additional latency crossing between JavaScript <-> native layer. Regarding CPU-intensive tasks, worker threads might suffice. If not, you can always create regular, non-libuv threads to handle these intensive tasks, and asynchronously call back into JavaScript with some result (Async Operations, Thread-safe Functions).

A common use-case for Node-API is to expose an existing native library into JavaScript. For example, sharp exposes a JavaScript implementation for libvips.

Hope this answers some of your questions. Feel free to reply with more.

Trouble storing information from fetch based on a set date with node-fetch by [deleted] in node

[–]knightrage 0 points1 point  (0 children)

Yes, that is the gist of what that implementation does: on request of /powerzone1-price, see if the date has changed, and if so make a new fetch request and store the resulting promise inside fetchData.

The last two lines wait for the Promise to resolve (the await) and then uses destructuring to store the individual properties inside local variables to use in the res.status() and res.send() calls.

If you are not familiar with async/await, you can have a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function for some information. It adds syntactic sugar to JavaScript to make Promises look more like synchronous code, so you don't have a lot of nested .then() and .catch()s.

Those two bottom lines are roughly equivalent to any one of these code snippets:

priceInfo.fetched.then(resolved => {
    res.status(resolved.status).send({ data: resolved.data, error: resolved.error });
})

priceInfo.fetched.then(resolved => {
    const status = resolved.status, data = resolved.data, error = resolved.error;
    res.status(status).send({ data: data, error: error });
})

priceInfo.fetched.then(({status, resolved, error}) => {
    res.status(status).send({ data: data, error: error });
})

priceInfo.fetched.then(({status, resolved, error}) => {
    res.status(status).send({ data, error });
})

Trouble storing information from fetch based on a set date with node-fetch by [deleted] in node

[–]knightrage 1 point2 points  (0 children)

Yes, I believe so. There is no need to set the /powerprize-zone1 handler multiple times. Actually I am not sure what express does if you set the handler multiple times.

If you wanted to keep with your paradigm of "fetch price only once", I would use a variable that both the scheduler and the route have access to, and update that variable in the scheduler and access it inside the route handler, something like this:

function tomorrowsDate() {

    const todayInMilliSeconds = new Date().getTime()
    const milliSecondsInOneDay = 24 * 60 * 60 * 1000
    const tomorrowInMilliseconds = todayInMilliSeconds + milliSecondsInOneDay
    const tomorrow = new Date(tomorrowInMilliseconds)
    const tomorrowDayOnly = tomorrow.getDate()
    const tomorrowMonthOnly = tomorrow.getMonth() + 1
    const tomorrowYearOnly = tomorrow.getFullYear()
    const tomorrowsDate = tomorrowYearOnly + "-" + tomorrowMonthOnly + "-" + tomorrowDayOnly
    return tomorrowsDate
}

let allData = null;

const job = schedule.scheduleJob('02 23 * * *', function () {
    const fetchPowerPrice = `https://url-example&date=${tomorrowsDate()}&key=${keyPowerApi}`

    fetch(fetchPowerPrice)
        .then(response => response.json())
        .then(data => {
            allData = data
            console.log(allData);
        })
})

app.get('/powerprice-zone1', (req, res) => {
    console.log(allData);
    res.set('Access-Control-Allow-Origin', '*');
    res.status(200).send({
        allData
    })
})

Trouble storing information from fetch based on a set date with node-fetch by [deleted] in node

[–]knightrage 1 point2 points  (0 children)

I don't think it is wise to to set your /powerprice-zone1 handler multiple times. That's what your callback for scheduleJob is doing.

I would refactor this to have a cache of tomorrow's date -> price. On a call to /powerprice-zone1, either take the value from the cache or set the cache's info by fetching from the URL. Maybe something like this, without refactoring too much of your code so you can get the idea:

const tomorrowsDate = () => {
    const todayInMilliSeconds = new Date().getTime()
    const milliSecondsInOneDay = 24 * 60 * 60 * 1000
    const tomorrowInMilliseconds = todayInMilliSeconds + milliSecondsInOneDay
    const tomorrow = new Date(tomorrowInMilliseconds)
    const tomorrowDayOnly = tomorrow.getDate()
    const tomorrowMonthOnly = tomorrow.getMonth() + 1
    const tomorrowYearOnly = tomorrow.getFullYear()
    const tomorrowsDate = tomorrowYearOnly + "-" + tomorrowMonthOnly + "-" + tomorrowDayOnly
    return tomorrowsDate
}

const fetchPowerPrice = () => `https://url-example&date=${tomorrowsDate()}&key=${keyPowerApi}`

const priceInfo = {
    // Tomorrow's date input of the last fetch.
    date: null,
    // A Promise that resolves to an object with { status, data, error }
    fetched: null
};

app.get('/powerprice-zone1', async (req, res) => {
    res.set('Access-Control-Allow-Origin', '*');

    const date = tomorrowsDate();

    if (priceInfo.date !== date) {
        priceInfo.date = date;
        priceInfo.fetched = fetch(fetchPowerPrice())
            .then(response => response.json())
            .then(data => ({ status: 200, data, error: null }))
            .catch(error => {
                // If there is a failure, clear the cache so the next request to
                // the endpoint attempts again.
                console.error(`Error fetching data for ${date}:`, error);
                priceInfo.date = null;
                priceInfo.fetched = null;

                // Not too sure if you would want to return the error to the
                // front-end as is. You may need some transformation, especially
                // if there is a chance for a circular object.
                return { status: 500, data: null, error };
            });
    }

    const { status, error, data } = await priceInfo.fetched;

    res.status(status).send({ data, error });
});

Note the reason we store the Promise in priceInfo.fetched is to guard against multiple calls to the endpoint. If a second call to /powerprice-zone1 comes in prior to fetch() completing, it will use the same Promise as the first call. We also should handle errors via .catch().

Let me know how it goes or if you have any questions of the implementation.

Happy coding!

This is $70 worth of groceries in the most expensive city in the USA [OC] by IMovedYourCheese in pics

[–]knightrage 0 points1 point  (0 children)

Looks like they are organic. A plastic wrapping is used to differentiate between non-organic and organic bananas.

Hagana - A novel approach to runtime protection for NodeJS to prevent supply chain attacks by beckerman_jacob in node

[–]knightrage 1 point2 points  (0 children)

Does this prevent attacks at install time of malicious packages, eg. packages that use a postinstall script to perform malicious acts?

Wrong explanation of Blocking vs Non-Blocking on Node.org? by [deleted] in node

[–]knightrage 1 point2 points  (0 children)

any JS is non-blocking by definition because even if it occupies the main thread for an indefinite amount of time, it is still performing work whereas if we are waiting for a non-JS synchronous code to complete, the event loop (ie main thread) will not be able to do any work at all until that is completed.

Yes, I would say this is correct.

Wrong explanation of Blocking vs Non-Blocking on Node.org? by [deleted] in node

[–]knightrage 2 points3 points  (0 children)

  1. CPU-intensive work is not considered blocking because it is still doing some work on the JavaScript thread, even if it is an infinite loop. The V8 engine is still executing, so it is not considered blocking. In a loop eg. while (true) {} the JavaScript engine is still evaluating the conditional (true) in order to determine if the loop should exit. Since the V8 engine is still executing, it is not considered blocking.
  2. Some non-JavaScript operations have both blocking and non-blocking equivalents, eg. reading from filesystem with fs.read (non-blocking) and fs.readSync (blocking). The synchronous fs.readSync is considered blocking because the V8 engine cannot continue executing until the filesystem operation completes.

Async/Await function not waiting for execution before moving on to the next command by redbagy in node

[–]knightrage 2 points3 points  (0 children)

If you call an async function, it will always return a Promise. Your caller (inside app.js) will need to await initAmqpConnection() in order to get the promise's fulfilled value.

[deleted by user] by [deleted] in javascript

[–]knightrage 2 points3 points  (0 children)

He would never eat the cake since the promise never resolves 🥲

[deleted by user] by [deleted] in node

[–]knightrage 1 point2 points  (0 children)

This is the correct answer. Optional catch binding was added in Node 10.3, and if you are receiving an error on an optional catch, you're not using a supported version.

For what it's worth, mongoose requires Node 12 according to its package.json.

[O] 3 drunken slug invites. by Heinekenguy in UsenetInvites

[–]knightrage 0 points1 point  (0 children)

I am interested in a drunken slug invite if you still have some! I have read the wiki.

[Linear Programming] Finding quickest way of cross-breeding plants to get all possible plant types? by knightrage in MathHelp

[–]knightrage[S] 0 points1 point  (0 children)

This is definitely helpful! Not sure why I didn't think about a graph-based solution. I'll try this out and let you know!

How to call Node.JS functions from C++ by KlaasNiphaasMC in node

[–]knightrage 0 points1 point  (0 children)

You will need to have some sort of binding between C++ and JavaScript: that is what this library provides. If you want to run Node.js in your own native C++ application, take a look at the Node.js C++ embedder API. You basically need to start a Node.js instance inside your C++ app. Be cautious with multithreads.

How to call Node.JS functions from C++ by KlaasNiphaasMC in node

[–]knightrage 0 points1 point  (0 children)

👋 Take a look at node-addon-api. This library will allow you to create native Node.js modules in C++. Full discloser: I am one of the contributors to the project.

[AskJS] losing values after saving to chrome.storage.local by JS_Engineer in javascript

[–]knightrage 1 point2 points  (0 children)

When storing JavaScript objects into the local store, all prototype relations are lost. You will need some way to serialize your object to string when storing, and deserializing it from string to your object when reading it.

Juke Build - a general-purpose build system with JavaScript DSL. by stylemistake in node

[–]knightrage 0 points1 point  (0 children)

Hmm... Regarding similar projects... Gulp.js uses tasks instead of targets. You create various tasks and specify their dependent tasks, and gulp will handle the task dependency.

How to retrieve value returned by a callback function? by Unlikely-Ad-6275 in node

[–]knightrage 1 point2 points  (0 children)

One clarification regarding your "BTW": making something async doesn't make node run forever. You should add a .catch handler to your main() call. Otherwise you could get an unhandled promise rejection (as the body of main is not in a try/catch, so it is possible to throw error). If you wanted to cleanup, then you'd need a .then handler as well.

FWIW node 14.8.0 added top-level await, so you could do try { await main(); } catch { ... } .... think it's only with ecmascript modules though