How do I use this package - xd-file? - node.js

I am trying to use this package to manipulate an Adobe XD file.
Link to the package: xd-file
I need to use this code snippet in a JavaScript file. I am using Node.js.
The method I need to use is readXDFile and the code snippet displayed in the Readme is:
(filePath: string) => Promise<{
document: Object,
interactions: Object,
metadata: Object,
resources: Object,
artboards: Array<Object>,
}>
What is the Javascript equivalent for this typescript code?
Thanks!
UPDATE
Here's the JS code that I wrote now:
var xdFile = require("xd-file");
filePath = './test/Test-1/XD-Test-1.xd'
xdData = xdFile.readXDFile(filePath)
console.log(xdData)
And here's the output:
Promise { <pending> }
How do I get the Object as the output?
RESOLVED
Replaced console.log(xdData) with:
xdData.then(
function (value) { console.log(value) },
function (error) { console.log(error) }
);
Thanks!

Base on what I understand it returns a promise, with that you should use what call asyns/await

Related

NodeJS + TypeScript Error TS2339: Property 'timeOrigin' does not exist on type 'Performance'

I have a NodeJS/TypeScript app that uses Selenium WebDriver, which has approximately this snippet:
import { WebDriver } from "selenium-webdriver";
export class MyClass {
public async getTimeOrigin(driver: WebDriver): Promise<number> {
return await driver.executeScript(function () {
// This should be the DOM's timeOrigin (same as if a person types "performance.timeOrigin"
// into the Chrome DevTools console)
return performance.timeOrigin;
});
}
}
When I attempt to build the above, I get the following error message:
error TS2339: Property 'timeOrigin' does not exist on type 'Performance'
But it does certainly exist, since I can looks up the references on the Performance object and see timeOrigin inside. Can anyone please advise on how to fix this and correctly access the timeOrigin property?
performance is a global variable which is only available to the web browser you test. While you're working in NodeJS environment, it doesn't have any global performance, that's why Typescript cannot detect it and throw the error when compiling.
To fix this, you only need a simple global variable declaration:
declare var performance: any;
If you're using a lot of web interfaces in your Node environment, I recommend you import the lib lib.dom to typescript to avoid these types of errors:
{
"compilerOptions": {
"lib": [
"dom"
]
}
}
As mentioned by mcernak, another way is to use string as input to executeScript function.
To avoid the compilation issues, you can provide the script that you want to execute in context of the browser as a string(instead of a function):
public async getTimeOrigin(driver: WebDriver): Promise<number> {
return await driver.executeScript("return performance.timeOrigin;");
}
From the documentation of WebDriver.executeScript:
Executes a snippet of JavaScript in the context of the currently
selected frame or window. The script fragment will be executed as the
body of an anonymous function. If the script is provided as a function
object, that function will be converted to a string for injection into
the target window.
Maybe you can try to cast it as Performance.
import { WebDriver } from "selenium-webdriver";
export class MyClass {
public async getTimeOrigin(driver: WebDriver): Promise<number> {
return await driver.executeScript(function () {
// This should be the DOM's timeOrigin (same as if a person types "performance.timeOrigin"
// into the Chrome DevTools console)
const perf = <Performance>performance; // or "performance as Performance"
return perf.timeOrigin;
});
}
}

TypeError: invNum.next is not a function

I have tried this code :
const invNum = require('invoice-number');
router.post('/checkout', async (req, res, next) => {
if (!req.session.cart) {
return res.redirect('/pos/');
}
var saleList = Sale.find().sort({ _id: -1 }).limit(1); // removed (err, data)=>{} to simply view it is working tested already
var settings = await Setting.find({}); // removed try and catch to simply view it is working tested already
var ticketNumber;
ticketNumber = !saleList ? invNum.next('0000000') : invNum.next(saleList.ticket_number);
var sale = new Sale({
ticket_number:ticketNumber,
cart: req.session.cart,
created_at: new Date()
});
sale.save((err, product) => {
createReceipt(settings, req.session.cart, "receipts/"+ticketNumber+".pdf");
req.session.cart = null;
res.redirect('/pos/');
});
});
I got this error:
TypeError: invNum.next is not a function
The problem is with invNum.next().
invNum.next() is a Node.js module to generate invoice number sequentially installed from npm.
Example:
invNum.next('2017/08/ABC001')
// => 2017/08/ABC002
I have tried already suggestions from previous stackoverflow posts by trying Promises or await async function in order to get this code to work. Hopefully, you can help or suggest something. Thank you.
There is a problem in version of invoice-number module. In the npm it is showing as 1.0.6 but in the GitHub repository it has 1.0.5 in the package.json file.
https://github.com/amindia/invoice-number.
I have tested this module by taking from Github repository and it's working fine.
Please take the source of this module from the given link it will works fine.
Seems to be some error in the module. I tried the below code snippet on RunKit
https://runkit.com/embed/ws2lv1y38mt4
var invNum = require('invoice-number')
try{
invNum.next('sdfsd1')
} catch(e){
console.log(e)
}
Getting the same error
I got this error:
TypeError: invNum.next is not a function UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
What is the output when you use the console.log on invNum?
Also use try catch and inside call invNum.next with await. Maybe something inside this function is throwing an error.
Edit: as jfriend00 says, if an plain text (like your "0000...") is working, probably the saleList is returning some error and you are not catching or treating the error.
Edit2: The last update on this NPM code is from 1 year ago and fewer people used this lib, probably is broken.
There is some part of the code from the index.js of the lib:
function _next (invoiceNumber) {
if (!invoiceNumber)
throw new Error('invoiceNumber cannot be empty')
var array = invoiceNumber.split(/[_/:\-;\\]+/)
var lastSegment = array.pop()
var priorSegment = invoiceNumber.substr(0, invoiceNumber.indexOf(lastSegment))
var nextNumber = alphaNumericIncrementer(lastSegment)
return priorSegment + nextNumber}
var api = { next: _next}
module.exports = api

Unable to use getElementsByTagName("body")

Here's the code that results in an error each time I run it. My goal is to scrap the content from the URL, remove all HTML, and return it:
console.log("Fetching: " + inputData.tweeturl);
fetch(inputData.tweeturl)
.then(function(res) {
return res.text();
}).then(function(body) {
var rawText = body.getElementsByTagName("body")[0].innerHTML;
var output = { id: 100, rawHTML: body, rawText: rawText };
callback(null, output);
})
.catch(callback);
The problem is with var rawText = body.getElementsByTagName("body")[0].innerHTML;
The error I receive is:
Bargle. We hit an error creating a run javascript. :-( Error:
TypeError: body.getElementsByTagName is not a function eval (eval at (/var/task/index.js:52:23), :16:24) process._tickDomainCallback (node.js:407:9)
Unfortunately - there is no JS DOM API in the Code by Zapier triggers or actions (that is because it isn't run in a browser and doesn't have the necessary libraries installed to fake it).
You might look at Python and instead, and https://docs.python.org/2/library/xml.etree.elementtree.html. Decent question and answer is available here Python Requests package: Handling xml response. Good luck!
Any function not supported by Zapier will result in a TypeError. I needed to use a regular expression to achieve this.

Typescript : Lost scope of 'this'

I'm trying to assign a value to myImage. When I look at the js target file myImage doesn't even exist. Obviously this throws an error. How do I preserve the scope of this within typescript classes?
What I'm trying to do here is load an image using the Jimp library. Then have a reference to that loaded image to perform operations on, for example resize is a method of a loaded image inside Jimp, so I'd like to be able to call i.myImage.resize(100,100).
"use strict";
var Promise = require('bluebird');
var Jimp = require("jimp/jimp");
class Image{
public myImage:any;
constructor(newImage:string){
Promise.all([new Jimp(newImage)]).then(function(img){
this.myImage = img;
}).catch(function(e){
console.log(e);
})
}
}
var i = new Image('./jd.jpg');
console.log(i.myImage)
The output:
undefined
[TypeError: Cannot set property 'myImage' of undefined]
With Callbacks :
var Jimp = require("jimp/jimp");
class Image {
public myImage: any;
constructor(newImage: string, typeOfImage: string) {
var self = this;
new Jimp(newImage, function(e,img) {
self.myImage = img;
});
}
}
var i = new Image('./jd.jpg');
console.log(i.myImage) // outputs undefined
The Jimp constructor does not return a promise so your use of Promise.all() here is likely not doing what you want it to do. As some people get confused by this, promises do not have any magic powers to somehow know when the Jimp object has finished loading it's image so if that's what you're trying to do here, it will not work that way. The Jimp constructor returns a Jimp object, not a promise.
I don't see any particular reason to not just use the Jimp callback that you pass into the constructor and make your code work like this:
var Jimp = require("jimp/jimp");
class Image {
private myImage: any;
constructor(newImage: string, typeOfImage: string) {
var self = this;
new Jimp(newImage, function(img) {
self.myImage = img;
// you can use the img here
});
// you cannot reliably use the img here
}
}
But, doing it this way looks like it still leaves all sorts of loose ends because the outside world has no way of knowing when the img has finished loading and you aren't saving the Jimp object reference itself so you can't use any of the Jimp methods on this image. As I said in my comments, if you share the bigger picture for what you're trying to do here, then we can more likely help you with a more complete solution to your problem.

Node-Webkit with external module containing native code

I'm using node-webkit with an external module called edge.
According to the node-webkit docs modules that contain native code must be recompiled using nw-gyp as oppose to node-gyp. I was able to recompile without error and node-webkit seems to import the module OK.
Heres my code. The code I'm trying to use:
var edge = require('edge.node');
var hello = edge.func(function () {/*
async (input) =>
{
return ".NET welcomes " + input.ToString();
}
*/});
hello('Node.js', function (error, result) {
if (error) throw error;
console.log(result);
});
Which throws the following error when run within node-webkit.
Uncaught TypeError: Object [object Object] has no method 'func'
If write the object out to console.log I can see:
Object {initializeClrFunc: function}
initializeClrFunc: function () { [native code] }
__proto__: Object
So the module seems to have loaded. If I run the same code outside of node-webkit, everything works perfectly and I can access the func function. This is driving me crazy - and any help would be really appreciated.
func method is provided by edge.js, the wrapper around edge.node native module. So you should replace require('edge.node') by require('edge').

Resources