I am trying to use the window.crypto.getRandomValues method in a nodejs script. From my understanding there is no window element when I run a simple code like this in node:
var array = new Uint32Array(10);
window.crypto.getRandomValues(array);
Which is why I get this error:
ReferenceError: window is not defined
How can I use this method in my code?
Thanks
You can use the built-in crypto module instead. It provides both a crypto.randomBytes() as well as a crypto.pseudoRandomBytes().
However it should be noted that these methods give you a Buffer object, you cannot pass in a Uint32Array or similar, so the API is a bit different.
const crypto = require('crypto').webcrypto;
let a = new Uint8Array(24);
console.log(crypto.getRandomValues(a));
This works almost exactly like the one in the browser, by adding webcrypto to the end of requrie('crypto');.
You can use this module which is the same as the window element: get-random-values
Install it:
npm install get-random-values --save
Use it:
var getRandomValues = require('get-random-values');
var array = new Uint32Array(10);
getRandomValues(array);
Here is how to use it in Node 16 with TypeScript. I'm hijacking the web types and overriding the #types/node type, which are missing webcrypto.
import { webcrypto } from 'crypto'
const crypto = webcrypto as unknown as Crypto
const random = crypto.getRandomValues(new Uint8Array(24))
This sandbox will work in Node 16, but stackblitz won't release node 16 for another couple months. https://stackblitz.com/edit/koa-starter-wychx9?file=package.json
Issue: github.com/denoland/node_deno_shims/issues/56
I had this problem too, I solved it this way
import * as crypto from 'node:crypto'
export function randomChar() {
return crypto.webcrypto.getRandomValues(new BigUint64Array(1))[0].toString(36)
}
reference:
How to use getRandomValues() in nodejs?
Related
I'm unable to get even the first lines of the example code from the relatively popular #kenjiuno/msgreader for parsing Outlook .msg files to work. I've installed the module with npm successfully, and my code is:
const fs = require('fs')
const MsgReader = require('#kenjiuno/msgreader')
const msgFileBuffer = fs.readFileSync('./test-email.msg')
const testMsg = new MsgReader(msgFileBuffer)
But I get the error: "MsgReader is not a constructor".
A quick console log of MsgReader returns { default: [Function: MsgReader] }. I also tried doing it as a function (no 'new' keyword) which also produced an error.
The only difference between my code and the example code is that they use import (import MsgReader from '#kenjiuno/msgreader') whereas I've used require, but presumably that couldn't make a difference?
Any ideas anyone?
I ended up changing the require statement to add ["default"] which fixed the issue:
const MsgReader = require('#kenjiuno/msgreader')["default"]
I looked at the library code and made a guess based on the export statement using that 'default' syntax. Is this issue something to do with commonJS or something? If anyone can explain this to me that would be great!
I'm enthusiastic about Deno so I'm giving it a try. Found a tutorial on building a REST API here.
So, when I'm trying to run it, I get this InvalidData error:
error: Uncaught InvalidData: data did not match any variant of untagged enum ArgsEnum
at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
at async Object.connect ($deno$/net.ts:216:11)
at async Connection.startup (https://deno.land/x/postgres/connection.ts:138:17)
at async Client.connect (https://deno.land/x/postgres/client.ts:14:5)
at async Database.connect (file:///Users/svenhaaf/git/deno/logrocket_deno_api/db/database.js:17:5)
Now, it looks to me that something is wrong when trying to connect to the database, but I can't really figure out what.
What does this InvalidData error mean? How should I fix this?
FYI my deno --version prints:
deno 0.42.0
v8 8.2.308
typescript 3.8.3
Code:
I cloned the repo from https://github.com/diogosouza/logrocket_deno_api, and in config.js, I edited line 1 from const env = Deno.env() to const env = Deno.env, since it looks like Deno.env became an object instead of a method.
The tutorial is not using versioned URLs, and deno-postgres version that is being used is not compatible with v0.42.0, since https://deno.land/x/postgres/mod.ts is pulling from master
Change db/database.js to import from https://deno.land/x/postgres#v0.3.11/mod.ts, since v0.3.11 is the correct version for Deno v0.42.0
import { Client } from "https://deno.land/x/postgres#v0.3.11/mod.ts";
Remember to always use the version in the URL if you don't want the code to stop working when a new Deno or package version is released.
I am using Angular 8, tslint 5.15 & typescript v3
I am reading file as ArryaBuffer using below code
const reader = new FileReader();
reader.readAsArrayBuffer(<FileObject>);
reader.onload = () => {
this.uploadedData= new Uint8Array(reader.result as ArrayBuffer);
}
Now when i pass this uploadedData into API, I am converting into byteArray using below fucntion.
convertLicenseToByteArray(uploadedData) {
const bytesArray = [];
for (const i of uploadedData) {
bytesArray.push(i);
}
return bytesArray;
}
The above code is giving error in ie11,
ERROR TypeError: Object doesn't support property or method
'Symbol(Symbol.iterator)_a.srxqdvyfxlx'
I tried to search on net and found that may be i need to add babel-polyfill but it's not working for me.
Any help?
add 'core-js' into you package.json and add import into your polyfills.ts
import 'core-js/es6/symbol';
IE11 doesn't support virtually any of ES2015+, so that means no arrow functions, no Symbol, and no iterables and iterators. (IE9-IE11 do support const and let, but not properly. They support an early version that isn't what was standardized. The biggest discrepancy is in regard to for loops.)
If you want to run that code on IE11, you'll need to transpile it to ES5 and add some polyfills. Symbol and iterability can't be properly polyfilled, but Babel and others provide something partially functional. I see here that Babel now recommends not using their own #babel/polyfill and instead using core-js directly (and regenerator runtime if you need to transpile generator functions).
The issue is relates to the uploadedData parameter, when we call the convertLicenseToByteArray method and use the uploadedData variable, if the data is not populated or undefined, it will display this error.
You could try to call the convertLicenseToByteArray method in the reader onload function.
const reader = new FileReader();
reader.onload = (_event) => {
this.uploadedData= new Uint8Array(reader.result as ArrayBuffer);
console.log(this.convertLicenseToByteArray(this.uploadedData).length);
}
For anyone that might be having this problem in an Aurelia project without typescript, I was able to solve it by installing core-js which included the polyfills needed to make this work.
npm install --save core-js#3.6.5
I then added the import in the .js file where I was having the issue and it started working.
import "core-js"
Is there a way to detect what version of Gulp is running (available to utilize in a gulpfile)?
I've got two separate gulpfile's I'm using amongst different environments, some that require v3 and some v4. For easier version control, I would prefer it if I could combine those files and not have to deal with different file names in different environments to eliminate confusion between multiple developers. Obviously to accomplish this I would need the script to differentiate between versions.
Alternatively to #alireza.salemian's solution, you could try to run the command line version command in javascript:
Depending on your JavaScript backend, your code may vary slightly, but inspired by this post you could run it as below:
const execSync = require('child_process').execSync;
// import { execSync } from 'child_process'; // replace ^ if using ES modules
const output = execSync('gulp -v', { encoding: 'utf-8' }); // the default is 'buffer'
const str_pos = output.search('Local version') + 14;
const gulp_version = output.substring( str_pos, str_pos + 5 );
console.log( 'Gulp version: ' + gulp_version );
You can read package.json and find gulp version
const pkgJson = fs.readFileSync('./package.json', { encoding: 'utf8' });
const pkg = JSON.parse(pkgJson);
const gulpVersion = pkg['devDependencies']['gulp'];
It may not be the best solution, but you can quickly determine the gulp version.
i am a newby on node.js. i want to parse a xml file into json .so i am trying to use bulebutton library from https://github.com/blue-button/bluebutton.js .
first i have installed the module by command npm install bluebutton and its created a node_modules folder with bluebutton module.
now i created a test.js file with following code
var bb = require('bluebutton');
var myRecord = bb.BlueButton('./asd.xml');
console.log(myRecord);
but its gave me an error that bluebutton is not define .please help me to figureout this problem thanks
REVISED ANSWER
From bluebuttonjs.com/docs, the require statement you use would return the BlueButton object, so bb represents said object, and it would be called like so
var myRecord = bb('someFile.xml');
However you might also note that they use fs to read the file before passing it. http://www.bluebuttonjs.com/docs/#parsing-node
PREVIOUS ANSWER (for wrong module)
According to their npm docs, you need to do
var bb = require('blue-button');
https://www.npmjs.com/package/blue-button