Require syntax equivalent of Import in Nodejs - javascript

I have an existing Nodejs application that still uses CommonJS, it's been fine up till now but I've ran into a module that I'm not sure how to import. I was hoping there was a fast way of doing it rather than restructuring my whole app to the module standard.
Here is the module's import documentation:
import MetaApi, {CopyFactory} from 'module.cloud-sdk';
const token = '...';
const api = new MetaApi(token);
const copyFactory = new CopyFactory(token);
I got the CopyFactory part to work by destructuring like so:
const { CopyFactory } = require('metaapi.cloud-sdk')
const copyFactory = new CopyFactory(token)
But I can't find a way to import the api aspect with the token, is there anyway of doing it?
Thanks a lot

You can do it this way,
const MetaApi = require('metaapi.cloud-sdk');
const {CopyFactory} = MetaApi;
const token = '...';
const api = new MetaApi.default();
const copyFactory = new CopyFactory(token);
Hopefully this will work fine.

As suggested by Bergi, adding default made it work
const { default: MetaApi, CopyFactory } = require(…)

Related

Editing an XML document

I am new to JavaScript and need the ability to create, edit and export an XML document on the server side. I have seen different options on the Internet, but they do not suit me.
It seems that I found one suitable option with processing my XML file into JSON, and then back and then export it through another plugin, but maybe there is some way to make it easier?
Thanks!
I recently came across a similar problem. The solution turned out to be very simple. It is to use XML-Writer
In your project folder, first install it via the console
npm install xml-writer
Next, first import it and create a new file to parse what's going on here:
var XMLWriter = require ('xml-writer');
xw = new XMLWriter;
xw.startDocument ();
xw.startElement ('root');
xw.writeAttribute ('foo', 'value');
xw.text ('Some content');
xw.endDocument ();
console.log (xw.toString ());
You can find more information here and at the bottom of the page see the different code for each item. In this way, you can create, edit and export xml files. Good luck and if something is not clear, write!
Additional
You will need also fs module
const fs = require("fs")
const xmlParser = require("xml2json")
const formatXml = require("xml-formatter")
Completed code:
const fs = require("fs")
const xmlParser = require("xml2json")
const formatXml = require("xml-formatter")
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startDocument();
xw.startElement('root');
xw.startElement('man');
xw.writeElement('name', 'Sergio');
xw.writeElement('adult', 'no');
xw.endElement();
xw.startElement('item');
xw.writeElement('name', 'phone');
xw.writeElement('price', '305.77');
xw.endElement();
xw.endDocument();
const stringifiedXmlObj = JSON.stringify(xmlObj)
const finalXml = xmlParser.toXml(stringifiedXmlObj)
fs.writeFile("./datax.xml", formatXml(finalXml, { collapseContent: true }), function (err, result) {
if (err) {
console.log("Error")
} else {
console.log("Xml file successfully updated.")
}
})
})

How to use bitcoin -rpcwallet flag in deno RPC

I want to create an address in a wallet with bitcoin-cli, the command for this will look like this for the loaded wallet bitcoin-cli getnewaddress some_users and with Deno I can just do
import { createRemote } from "https://deno.land/x/gentleRpc/rpcClient.ts";
let Node = new URL("http://127.0.0.1:8332");
Node.port = "8332";
Node.username = "some_user";
Node.password = "some_password";
const remote = createRemote(Node);
const address = remote.getnewaddress(addressLabel);
I would love to know how to use deno rpc for cases where I need to specify the -rpcwallet flag, like this bitcoin-cli -rpcwallet=some_unique_wallet getnewaddress some_users
So after reading the doc further, I realised I can do this by passing the wallet name to the url like this http://127.0.0.1:8332/wallet/${walletName} or just this http://127.0.0.1:8332/wallet/ for the default wallet.
So the code will look like this,
createConnection(walletName?: string) {
const uri = !!walletName ?
'http://127.0.0.1:8332/wallet/${walletName}' :
'http://127.0.0.1:8332/wallet/';
let Node = new URL(uri);
Node.port = "8332";
Node.username = "some_user";
Node.password = "some_password";
return createRemote(Node);
}

Importing locators in puppeteer tests using const

I have an object repository file where I store all the locators. However to improve maintainability and readability, I am now grouping the locators using const. For example:
const delivery = {
DELIVERY_HEADING: "xpath=//div[OOtext()='Delivery']",
DELIVERY_COUNT: '.bit-deliverylistrow'
};
const operations = {
SAVE_AUD: '.bit-save-btn',
SAVE_AUDNAME: "xpath=//*[text()='Audience name']/../input"
};
module.exports = { delivery, operations }
In the tests, I am using importing and using them as:
const or = require('../TestData/OR');
await page.focus(or.delivery.DELIVERY_HEADING);
await page.type(or.operations.SAVE_AUDNAME,'hello');
Is there a way I don't have to refer to the const and directly call the object locators in the test as it is difficult to identify which const has which locator ?
I would like to do await page.focus(or.DELIVERY_HEADING)
Any pointers will be helpful.
You can use the spread ... to create a single object.
module.exports = { ...delivery, ...operations }
Now you can do,
await page.focus(or.DELIVERY_HEADING)

Can uglify-js remove require and export statements?

I'm using uglify-js to minify the source code. I want to remove
const moment = require('moment');
const PouchDB = require('pouchdb');
module.exports = Chart;
statements of the original source code. Is it possible? Or is there any other compressor tool supports this?
I use the code as below in Node.js.
'use strict'
const moment = require('moment');
const PouchDB = require('pouchdb');
const defaultcachetime = 12; // hours
const VERIFIED = 3;
const UNIQUCOUNTER = 1;
var caches = {};
var cachechange = {};
function Chart(path, credentials, user){
}
module.exports = Chart;
The output contains
"use strict";const moment=require("moment"),PouchDB=require("pouchdb") return a},module.exports=Chart;
Thank you for helping
Managed to overcome the challenge by doing
Browserify to convert Require and Import keywords to FE parsable code.
Minify JS code with Uglify
Hope it helps with anyone who might be facing the same challenge.

module.exports won't export object with function

I've made a ModulesManager to manage all my modules, so I don't have a huge list of requirements in the top of my "server.js", but every time I'm trying to access the manager's methods, my server crash and throw an error which is saying that my manager method isn't a function.
TypeError: moduleManager.sqlString is not a function
I'm not really sure what I'm doing wrong here, this might be a stupid error, I've tried to look online for an answer but everyone is saying something different and nothing work.
Modules Manager (manager.js):
const sqlSetup = require("./sqlSetup.js");
const sqlSafeString = require("./sqlString.js");
function Manager(){
this.sqlString = function(query){
return sqlSafeString.getSqlSafeString(query);
},
this.sql = function(){
return sqlSetup;
}
}
module.exports = Manager;
Module SQL (sqlSetup.js):
const SqlString = require('sqlstring');
function getSqlSafeString(query){
//format query to fit in MySQL
var format = SqlString.escape(query);
return format;
}
module.exports = getSqlSafeString;
This is a test for my Travis build that I'm trying to make, the module manager path is good, the problem is really in the "ModuleManager.js" which I don't understand...
require('dotenv').config();
const Discord = require("discord.js");
const client = new Discord.Client();
const token = process.env.MOISTY;
const moduleManager = require("../modules/manager.js");
const assert = require("assert");
console.log("MAKE SURE MOISTY IS OFFLINE!");
client.login(token);
client.on('ready', () => {
//confirm login
console.log("MOISTY:200");
//Assert
assert.deepEqual(moduleManager.sqlString("sample text"), "sample test");
//terminate the session
process.exit();
});
I'm not very used to module exports, so this might be an easy question...
There are multiple mistakes in your code.
module.exports = getSqlSafeString; sets the export to getSqlSafeString.
When you do require("./sqlString.js") you will get the value that was assigned to the exports so in your case the getSqlSafeString.
So if you want to access that function you would write:
const getSqlSafeString = require("./sqlString.js");
//...
return getSqlSafeString(query);`
module.exports = Manager; exports the function Manager but not an object of the type Manager, so moduleManager.sqlString would be equal to Manager.sqlString. If you only want to group the functions in one object, then using a constructor would not make much sense here anyway, so you should write it that way:
module.exports = {
sqlString : function(query){
return sqlSafeString.getSqlSafeString(query)
},
sql : function(){
return sqlSetup
}
};
If you really want to do create on Object of the type Manager then you need to write:
module.exports = new Manager
For you to be able to require something from module A at module B, you have to export that something at module A. You export it assigning it to module.exports.
Yout problem is you didn't export the Manager at the Manager module.
You could simple export Manager, but, because you seem to be using an instance of Manager:
const moduleManager = require("../modules/manager.js");
...
moduleManager.sqlString("sample text")
Then you must export an instance. Add to manager.js:
module.exports = new Manager();
You are putting the functions on an instance, ie this.sqlString is a property named sqlString on an instance of Manager. But you are not using Manager as a constructor, ie not doing new Manager() or in your case new moduleManager()
You can change your import code to like below
const moduleManager = new require("../modules/manager.js")();
Or change the export to:
module.exports = new Manager();
Then moduleManager will be an instance of Manager and will be able to use moduleManager.sqlString

Categories