Uncaught TypeError: URL is not a constructor using WHATWG URL object support for electron - node.js

I am trying to read a file using WHATWG URL object support here
and I am getting this error: Uncaught TypeError: URL is not a constructor
here is my code:
var fs = require("fs");
const { URL } = require('url');
var dbPath = 'file://192.168.5.2/db/db.sqlite';
const fileUrl = new URL(dbPath);

I faced the same issue, then I looked into the url module and found a solution
For Node V6 use,
const URL = require('url').Url;
or
const { Url } = require('url');
If you look into the module, it exports 5 methods one of which is Url, so if you need to access Url, you can use either of the two methods

Are you using Node 6 instead of Node 8?
Node 6
const url = require('url');
const myUrl = url.parse('http://example.com');
const myUrlString = url.format(myUrl);
https://nodejs.org/dist/latest-v6.x/docs/api/url.html#url_url
Node 8
const { URL } = require('url');
const myUrl = new URL('http://example.com');
const myUrlString = myUrl.toString();
https://nodejs.org/dist/latest-v8.x/docs/api/url.html#url_url

Node v10.0.0 and newer (currently Node v19.x)
URL Class
v10.0.0 | The class is now available on the global object.
As mentioned here: Node.js Documentation - Class: URL
So this should work without require('url'):
const myUrl = new URL('http://example.com');

The docs you took this info out are for the node of version 8.4.0.
If it does not work for you, that means that your node is of version 6.11.2. Then, just change the letter case of URL -
const { Url } = require('url');
const myUrl = new Url('http://example.com');
because url module exports Url, not URL.

Related

Shopify API Node/Express Cannot read properties of undefined (reading 'Rest')

Just starting off with Shopify, and trying to get an order. Following the Shopify API documentation, here is my code:
const Shopify = require('#shopify/shopify-api');
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
module.exports.getShopifyOrderById = async (orderId) => {
return await client.get({
path: `orders/${orderId}`,
});
}
I get the following error when I execute this code:
TypeError: Cannot read properties of undefined (reading 'Rest')
Can't seem to figure out what the issue is.
You need to use Object destructing to get the Shopify object or use default export like below.
const { Shopify } = require('#shopify/shopify-api');
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
OR
const Shopify = require('#shopify/shopify-api').default;
const client = new Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
OR
const ShopifyLib = require('#shopify/shopify-api');
const client = new ShopifyLib.Shopify.Clients.Rest('my-store.myshopify.com',
process.env.SHOPIFY_KEY);
This has to do with how ES6 modules are emulated in CommonJS and how you import the module. You can read about that here.

streaming a remote image to the buffer using Koa

First time playing around with nodejs streams.. I feel like I'm missing something fundamental here about how streams work. When I make the request to the URL it logs out a 404. If I try to write to the buffer it throws an error.
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type object
1 const Koa = require('koa')
2 const app = new Koa()
3 const fs = require('fs')
4
5 const url = 'http://4.bp.blogspot.com/-cDeYCsNL-ZQ/UozsUJ7EqfI/AAAAAAAAGSk/EtuzOVpHoS0/s400/andy.png'
6 app.use(ctx => {
7 const buffer = new Buffer.alloc(1000)
8 ctx.request.get(url).pipe(fs.createWriteStream(buffer))
9 console.log(ctx.request)
10 console.log(ctx.response)
11 })
12
13 app.listen(1337)
The error is caused by this part: fs.createWriteStream(buffer). That method expects a string that contains a filesystem path, e.g. fs.createWriteStream("image.png").
On a general level, your usecase doesn't require explicitly creating any Buffers. Even Koa is redundant. If you'd like to stream contents of an URL to hard disk using Buffers behind the scenes. You can write:
const request = require("request")
const fs = require("fs")
const url = 'http://4.bp.blogspot.com/-cDeYCsNL-ZQ/UozsUJ7EqfI/AAAAAAAAGSk/EtuzOVpHoS0/s400/andy.png'
request(url).pipe(fs.createWriteStream('image.png'))

url.searchParams returns undefined in node.js

In the following node.js example:
var url = require('url');
var urlString='/status?name=ryan'
var parseObj= url.parse(urlString);
console.log(urlString);
var params = parseObj.searchParams;
console.log(JSON.stringify(params));
the property searchParams is undefined. I would expect searchParams to contain the parameters of the search query.
As you see in https://nodejs.org/dist/latest-v8.x/docs/api/url.html#url_class_urlsearchparams
searchParams is a proxy to an URL object. You must obtain a new URL complete object (with domain and protocol) and then you can use searchParams:
var url = require('url');
var urlString='https://this.com/status?name=ryan'
var parseObj= new url.URL(urlString);
console.log(urlString);
var params = parseObj.searchParams;
console.log(params);
Other way is using the query attribute (you must pass true as second parameter to url.parse):
var urlString='/status?name=ryan'
var parseObj= url.parse(urlString, true);
console.log(parseObj);
var params = parseObj.query;
console.log(params);
It is recommended to use: var parsedUrl = new URL(request.url, 'https://your-host'); instead of url.parse
url.parse shouldn't be used in new applications. It is deprecated and could cause some security issues: as stated here

KOA POST parsing error

I'm trying to get the POST data using koa-body-parser but I get the following error :
SyntaxError: Unexpected token e
at Object.parse (native)
This error refer to
/co-body/node_modules/raw-body/index.js
I think that the library co-body is trying to use "parse" but in my node version this function is restricted.
I'm using node 0.11.13
This is a part of the app.js
var path=require('path');
var koa = require('koa');
var app = koa();
app.use(require('koa-body-parser')());
//enrutamiento
app.use(require('./configs/routes')(app));
This is the function that recibe the call:
function *(){
/*
var str = 'email=lopezchr%40gmail.com&password=123123';
console.log(JSON.parse(str));
*/
var self = this;
var attributes= this.request.body
var userModel = this.models.user;
userModel.create(this.request.body).exec(function(){
self.body={success:true,description:"user Created"}
});
}
Aditionally, when I try to do this:
var str = 'email=lopezchr%40gmail.com&password=123123';
console.log(JSON.parse(str));
I optain the same error..
update
In other post, I realized that string is not a JSON.. sooo... that is the problem...
I'm trying to do this:
$.post('/auth',$(form).serialize(),function(data){
console.log(data);
});
And I want to recibe the form data with koa-body-parce...What should I do?
For some reazon, the jquery function $.post was sending the message with type json.. so that caused the error.. now the message type is plain/text and works.. thanks

How can I allocate URL objects in node.js?

How can I allocate an instance of a URL object using node.js from an existing url string?
Something like this:
var url = require('url');
var myurl = new url("http://google.com/blah");
I can't seem to find any mention/example of this anywhere.
var url = require('url');
var myurl = url.parse('http://google.com/blah');
You can now use
myurl.hostname // google.com
myurl.pathname // /blah
and so on..
http://nodejs.org/api.html#url-302
You very rarely (if ever) need to use the new keyword in relation to the built-in modules, as long as you use the documented functions.

Resources