How can i use ‚momentjs‘ in a ‚binary-parser‘ formatter? - node.js

Can anybody help me please. How can i use moment in a formatter?
i think this is not a problem from node or binary parser. it is my understanding i think.
const Parser = require("binary-parser").Parser;
const moment = require('moment');
let time = function(timestamp) {
return moment(timestamp, 'YYMMDDHHmmssSS').format('YYYY-MM-DD HH:mm:ss.SS');
};
let Telegram = new Parser()
.string('timestamp', {encoding: 'hex', length: 7, formatter: time});
The Exception is:
evalmachine.:9
return moment(timestamp, 'YYMMDDHHmmssSS').format('YYYY-MM-DD HH:mm:ss.SS');
^
ReferenceError: moment is not defined
at Parser. (evalmachine.:9:2)
...
I think the Problem is that Parser don't know moment. But how can i realize that?
i have tried to import moment directly in the binary-parser module. But it doesn't working.
If i run moment outside of Parser then it is working.
Maybe anybody can help me.

The formatter function runs without the momentjs context. I am guessing because of the way it consumes the formatter property. In the code found here, the code is:
if (this.code.formatter) {
... (ctx, varName, this.options.formatter)
Because of the funny way the this keyword works, it's bound to the object (options) and because that declaration does not contain momentjs, it says that it is not defined.
You can get a better understanding of this by looking at line 735:
ctx.pushCode("{0} = ({1}).call(this, {0});", varName, formatter);
It's bound to the current object.
P.S.: I copied the code and pasted it on Node.js and it's working perfectly. ^That is a possible explanation.

Related

Using randomUUID() in Zapier to generate UUID

I'm using Zapier's code module to write some Nodejs to generate a UUID.
I know that I can use node's crypto "library" because I've used it in the past to hash some text (MD5) to send to an API endpoint. I also know that I can use the crypto function randomInt.
For example, the following will correctly without errors return a number in the stated range:
const crypto = require('crypto');
let num = crypto.randomInt(1, 7);
output = [{id: num}];
When I try to use the randomUUID function (documentation), like the following, I get the error "TypeError: crypto.randomUUID is not a function" from Zapier:
const crypto = require('crypto');
let uuid = crypto.randomUUID();
output = [{id: uuid}];
I almost gave up there, but tried one last weird thing:
const crypto = require('crypto');
let uuid = crypto.randomUUID; //changed this
output = [{id: uuid}];
Note that I removed the () and this didn't throw an error and returned something like:
LT6TvivKgpFu5Yk3OvQmti1Hq1aNy5ZM
That looks a lot like a proper UUID since it has the right number of characters, but not the expected hyphens like (for example) 88368f2a-d5db-47d8-a05f-534fab0a0045
So, two questions:
Why is Zapier saying that randomUUID() is not a function? Does it not support this or am I coding something weirdly wrong or not requiring something needed? Is there a different way to do this?
When I use randomUUID (no ()) is this actually a reliable UUID?
EDIT: more info from Zapier, they are saying that their logs show that the code step cannot find module 'uuid'
When I use randomUUID (no ()) is this actually a reliable UUID?
The value you're getting there is not a reliable UUID. UUIDs will contain only 0-9a-f characters, the example you have there doesn't match.
Sorry I can't help you with what's going wrong with the other part! You could maybe try something like this
let crypto;
try {
crypto = require('crypto');
} catch (err) {
console.log('crypto support is disabled!');
}
to make sure the crypto package is actually available and there's not some error being silently suppressed? You may also want to check the version, as randomUUID() appears to have been added in v14.17.0
Also nit but should probably be const uuid = crypto.randomUUID(); instead of let ;)

tsnode with new AsyncFunction gives error

const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor
const fn = new AsyncFunction('a','await blah')
So I'm trying to create a function using new AsyncFunction
This is working perfectly on the server. But when I do tsnode script.ts, I got
SyntaxError: await is only valid in async functions and the top level bodies of modules
for the exact line.
Somehow tsnode is creating a normal function instead of an async one. Is there any trick around this?
In my case, the exact fn defintion in string is:
`try{ ${js}\n return await ${fnName}(${args}) \n}catch(err){console.log('err ',err)}`
So if I get rid of await, it works ie
`try{ ${js}\n return ${fnName}(${args}) \n}catch(err){console.log('err ',err)}`
Still doesn't resolve the main tsnode async-fn creation problem, but this is a trick that unstucks me

ESLint no-undef on ES6 function with named arguments

I have a function defined like this:
const generate = (report={}, buffer=false) => {
// do stuff
}
Notice how both of the parameters have default values.
When I call that function and name an argument I get a no-undef ESLint error.
generate(buffer = true);
ESLint says that "buffer" is not defined. It's not detecting that it is a named argument. Does anyone know how to change my .eslintrc to account for named arguments. I can't find anything online.
Thanks in advance!
What you are expecting from this code does not exists in Javascript.
You are getting no-undef ESLint error because buffer is never declared. Since there are no named params in JS, you could just call generate(true).
Although that would actually result in report being equal to true and buffer being settted to its default, which you have setted tofalse.
To achieve something closer to what you are looking for, you could switch the variable orders:
generate(buffer = false, report = {})
And then calling generate(true) would cause a call having the parameters:
buffer = true and report = {}.
Hope that makes sense.
For further reading, I recommend: http://2ality.com/2011/11/keyword-parameters.html

How do I solve ReferenceError: regeneratorRuntime is not defined

I've seen that issue a lot here but none of the solutions worked for me. I'm using NodeJS and had no issue until I changed the project's directory.
Since then I can't get my code to work...
I've included:
import "#babel/polyfill"
I'm using async / await and this is clearly what's causing the issue:
async function process_data(post) {
// my_code
}
If I write the code like that:
const test = async function process_data(post) {
// my code
}
That's working but I can no longer call the process_data method on its own with the parameter (or else, I don't know how do it).
Any idea how I can get that to work?
By tweaking the code I found the answer:
const my_func = async function process_data(post) {
// my code
}
var res = my_func(post_var);

Electron app: Reference mainWindow object in another module?

I am building an electron app, where the mainWindow object is created following the quick start: http://electron.atom.io/docs/tutorial/quick-start/.
As per this quick start, it is created asynchronously. The problem that I run into, is that for instance when I want to send messages from main to renderer process, I need to reference the mainWindow object. If this happens to be in a module that I require, then I need a means to make this module know of the mainWindow object.
I could of course prepend it with global., but I know that this is very much advised against. So I wish to do it more elegantly.
I came across this post: Asynchronous nodejs module exports; which appears to offer a solution. Taking the main.js file from the quick start (see above link, it's explicitly shown there), it appears I would add to the createWindow function
if( typeof callback === 'function' ){
callback(mainWindow);
}
and export the main.js module as
module.exports = function(cb){
if(typeof mainWindow !== 'undefined'){
cb(mainWindow);
} else {
callback = cb;
}
}
Then, in a higher-level script, I would require as follows:
let main = require('./main.js');
let lib = require('./lib.js'); // Library where I need a mainWindow reference
main(function(window) {
lib.doSomething(window);
});
where lib.js looks like
module.exports.doSomething = function(window) {
// Do something with window object, like sending ipc messages to it
window.webContents.send('hello-from-main', "hi!");
}
Although the simple case in the original post 'Asynchronous nodejs module exports' works fine, I cannot get it to work like described above; running the app it complains Uncaught Exception: TypeError: Cannot read property 'webContents' of null. This is also the case if I directly require lib.js within main()'s callback (which I know is also advised against).
I confess that I do not fully understand the simple case of the post, as I am rather new to node. This prevents me from fixing my own implementation of it, which I agree is blunt copy/pasting which reasonably should be expected to fail. Could somebody help me with how to correct above method, or advise me of a different approach to make it work? Thank you!
I have created the npm package electron-main-window for the same.
Install:
$ npm install electron-main-window
or
$ yarn add electron-main-window
Usage:
// Import ES6 way
import { getMainWindow } from 'electron-main-window';
const mainWindow = getMainWindow();
// Import ES5 way
const mainWindow = require('electron-main-window').getMainWindow();
// e.g:
if(mainWindow !== null ){
mainWindow.webContents.send('mainWindowCommunication', "This is a test message");
}
Whooops! The devil is in the details... I had defined on top of main.js
let mainWindow = null, callback;
which caused the error! Should be
let mainWindow, callback;
then it works perfectly!
P.s. Instead of deleting my post, I opted for keeping it and answering myself for future reference of other people who need asynchronous exporting.

Resources