Not able to Display Data properly in node cli-table - node.js

I'm trying to display data that i received from an api on console using cli-table. The api call and everything works fine. I'm just having trouble displaying the output. Here's my code
const
url = require('./url'),
Table = require('cli-table2'),
fs = require('fs'),
inquirer = require('inquirer')
let table = new Table({
head: ['Name', 'Type', 'Language',
'Genres', 'Status', 'Premiered', 'OfficialSite', 'Schedule', 'Rating', 'Streamed On', 'Externals', 'Images', 'summary'
],
colWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
});
const search = (item) => {
let shows = []
url.wordsearch(item)
.then(result => {
//console.log(result)
result.forEach(element => {
shows.push({ 'name': element.show['name'], 'value': element.show['id'] })
})
//console.log(shows)
inquirer.prompt([{
type: 'checkbox',
message: 'select tvshows you want see',
name: 'tvshow',
pageSize: 25,
choices: shows,
validate: (answer) => {
if (answer.length < 1) {
return "You must choose at least one card";
}
return true;
}
}]).then((answer) => {
//console.log(answer)
printresult(answer)
})
})
.catch(err => console.log(err))
}
const printresult = (answer) => {
answer.tvshow.forEach(show => {
url.idsearch(show)
.then(element => {
clean(element)
table.push([element['name'],
element['type'],
element['language'],
element['genres'],
element['status'],
element['premiered'],
element['officialSite'],
`Time :${element['schedule']['time']} \n Days: ${element['schedule']['days']}`,
element['rating'],
` name:${element['network']['name']}\n Country: ${element['network']['country']}`,
`tvrage:${element['externals']['tvrage']}\n thetvdb:${element['externals']['thetvdb']}\n imdb:${element['externals']['imdb']}`,
`medium:${element['image']['medium']}\n original:${element['image']['original']}`,
element['summary']
])
console.log(table.toString())
})
})
}
What am I doing wrong ? I want the output in a proper table format with no ... or anything. The printresult method does the work of printing to the console. I'm attaching a screenshot of my output.

Related

Discord.js | How to create a limit of .addFields objects, creating a list with .addFields with different value of an Array?

I created a script to do tests, I want to make a listing with 4 objects inside the .addfields, if you have more than 4, create an embed throwing other data in the objects inside the .addfields in it.
const Command = require("../../structures/Command");
const { EmbedBuilder, ModalBuilder, TextInputComponent, ButtonBuilder, ButtonStyle, ApplicationCommandType, ActionRowBuilder, SelectMenuOptionBuilder, SelectMenuBuilder} = require('discord.js');
module.exports = class extends Command {
constructor(client) {
super(client, {
name: 'shop',
description: 'shop',
type: ApplicationCommandType.ChatInput
});
};
run = async (interaction) => {
let listItems = ['Whinds', 'Freeway', 'Teste', 'Maria'];
const embed = [];
let i = 0;
listItems.forEach(e => {
if (!embed[Math.floor(i / 60)]) {
embed.push(new EmbedBuilder()
.setDescription(`testando`)
.addFields(
listItems.map(item => (
{
name: `${item[i]} [R$ ${item[i]}]`, value: `${item[i]}`}
))
)
);
}
i++;
})
console.log(embed)
embed.forEach(e => {
interaction.reply({embeds: [e] });
})
}
}
I would like support, how can I make this listing system with a maximum of 4 objects in the embed addfields.

Got stripe.error.InvalidRequestError: Request "random_string": Invalid object while creating a stripe-payment session in python

This is an App code
#app.route("/stripe_pay")
def stripe_pay():
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
'price_data': 'my_price_id',
'quantity': 1,
}],
mode='subscription',
success_url=url_for('index', _external=True) + '?session_id={CHECKOUT_SESSION_ID}',
cancel_url=url_for('add_service', _external=True),
)
return {
'checkout_session_id' : session['id'],
'checkout_public_key' : app.config['STRIPE_PUBLIC_KEY']
}
I have tried to make money transactions in my app and watched this [tutorial][1]. I have checked all my secret_keys and imported everything that the app needs.
A debugger argues cancel_url=url_for('add_service', _external=True),.
This is my a JS code
button.addEventListener('click', event => {
fetch('/stripe_pay')
.then((result) => { return result.json(); })
.then((data) => {
var stripe = Stripe(data.checkout_public_key);
stripe.redirectToCheckout({
sessionId: data.checkout_session_id
}).then(function (result) {
});
})
});```
*Thank you in advance*
[1]: https://www.youtube.com/watch?v=cC9jK3WntR8&t=7s
If you have a price ID already, you should be using price in your line_items, not price_data which requires some child parameters.
https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-line_items-price

node.js "Usage of deprecated field: 'series'" while using c3 chart maker

I am using c3 chart maker following the instructions of this github project: https://github.com/ashleydavis/nodejs-chart-rendering-example.
I would like to create a chart from a .csv data, however when i run the code below the chart is empty and I have this message: "Usage of deprecated field: 'series' ".
const c3ChartMaker = require('c3-chart-maker')
const inputFilePath = "./test_file.csv"
const chartDefinitionFile = "./chart.json"
const outputFilePath = "./chart.png"
c3ChartMaker(inputFilePath, chartDefinitionFile, outputFilePath)
.then(() => {
console.log('done')
})
.catch(err => {
console.error(err)
})
i test your code with this example: https://github.com/ashleydavis/c3-chart-maker
i use example-chart.json and example-data.csv in example folder and this is my code:
const c3ChartMaker = require('c3-chart-maker')
const inputFilePath = "./example-data.csv"
const chartDefinitionFile = "./example-chart.json"
const outputFilePath = "./example-js.png"
c3ChartMaker(inputFilePath, chartDefinitionFile, outputFilePath)
.then(() => {
console.log('done')
})
.catch(err => {
console.error(err)
})
when i run this code show me this image:
and on my console i have this message:
Usage of deprecated field: 'series'.
done
i read index.js code in node_modules\c3-chart-maker directory and find something:
if (chart.series) { // THIS SECTION IS DEPRECATED.
console.error("Usage of deprecated field: 'series'.");
if (!chart.data.columns) {
chart.data.columns = [];
}
var series = Object.keys(chart.series);
var dataFrame = new dataForge.DataFrame(data);
series.forEach(seriesName => {
var dataSeries = chart.series[seriesName];
if (Sugar.Object.isString(inputData) && seriesName !== "x") {
dataFrame = dataFrame.parseFloats(dataSeries).bake();
}
chart.data.columns.push(
[seriesName].concat(
dataFrame.getSeries(dataSeries)
.select(v => v === undefined ? null : v)
.toArray()
)
)
});
}
you see this error log: Usage of deprecated field: 'series'. because in example-chart.json file we have this line of json:
"series": {
"x": "Date",
"Close": "Close",
"Volume": "Volume"
},
and series is deprecated.

How to generate tables rows dynamically in Nodejs using ESCPOS API module

A few days ago I was struggling to get to print receipts using ESCPOS Java API but failed since I couldn't find a simple enough USB API to allow the program to print to my thermal printer using a USB interface. I later decided to implement this in Node and ESCPOS module.
I am connecting this application to MySQL database to be able to print receipts from recorded transactions. I am using tables to create a list of products and their respective prices but only by hard coding. My problem now is how to create these tables dynamically. Depending on which products were involved in the transaction, I want the script to query and print only those.
Here is receipt code!
const db = require('./database.js');
const escpos = require('escpos');
const uniqueRandom = require('unique-random');
const random = uniqueRandom(1000, 9999);
const device = new escpos.USB();
const options = { encoding: "GB18030" }
exports.printGeneralReceipt = function(status){
db.getTransactionDetails(function(res){
data = res;
});
const printer = new escpos.Printer(device, options);
console.log("Printer found!");
device.open(function(){
console.log("Receipt generating...");
printer
.font('b')
.align('ct')
.style('bu')
.size(1, 1)
.encode('utf8')
.text('\n*****START OF LEGAL RECEIPT*****'+
'\n\nCOMPUTICKET MALAWI\n'+
'SHOP 31A, GAME COMPLEX\n'+
'LILONGWE MALL\n\nwww.computicket.mw\n+265 (0) 99 974 7576\n')
.table(["BUYER NAME :", "CLIFFORD MWALE", ""])
.table(["RECEIPT # :", random(), ""])
.table(["DATE: ", "12/AUG/2019", ""])
.text("----------ITEM LIST----------\n")
// ITEM LIST STARTS HERE
.table(["MILK","$2"])
.table(["PEANUT BUTTER", "$6"])
// ITEM LIST ENDS HERE
.text("--------------------------------")
.table(["TOTAL PRICE", "$8.00", ""])
.text("Operator: Jon Doe\n-------------------------------\n")
.barcode('123456789012')
.text("\n\nTHANK YOU\n\n*****END OF LEGAL RECEIPT*****")
.beep(1,100)
.cut().close();
console.log("Receipt printed!");
});
}
And here is the function pulling the transaction details from the Database. I'll spare you the overhead of creating a connection.
exports.getTransactionDetails = function(trans_id){
var res = "";
conn.query("SELECT * FROM transactions JOIN products_in_transaction WHERE transactions.trans_id = products_in_transaction.trans_id "+
" transactions.trans_id = '"+trans_id+"'",
function (error, results, fields) {
for(var i = 0; i < results.length; i++){
// SOME OPERATION HERE
}
});
}
I will post some code I played with, and it worked;you need to install html-to-text
const escpos = require('escpos');
// Select the adapter based on your printer type
const device = new escpos.USB();
const printer = new escpos.Printer(device);
const cartItems = [
{category: 'test', price: 80, quantityToSell: 2, title: 'Hosting'},
{category: 'test1', price: 820, quantityToSell: 63, title: 'Mouse'},
{category: 'test00', price: 60, quantityToSell: 20, title: 'Sale'},
{category: 'dvhfgnfgjfjg', price: 20, quantityToSell: 8, title: 'Keyboards'},
{category: 'dvhfgnfgjfjg', price: 10, quantityToSell: 4, title: 'Keyss'},
{category: 'dvhfgnfgjfjg', price: 70, quantityToSell: 1, title: 'Test'},
{category: 'dvhfgnfgjfjg', price: 500, quantityToSell: 12, title: 'Whale oil'},
{category: 'dvhfgnfgjfjg', price: 560, quantityToSell: 22, title: 'Papers'},
]
// get total per line items
const totalPerItemList = (item) => {
let totalPerItem = 0
totalPerItem = item.quantityToSell * item.price
return totalPerItem
}
// get the total price
let total = 0;
for (let cartItem of cartItems) {
var unitSum = cartItem.quantityToSell * cartItem.price
total += unitSum
}
// Create our html template, could be an html file on it's own
const TestTable = `
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Testing Title for table</title>
</head>
<body>
<div class="invoice-box">
<table class="receipt-table" cellpadding="0" cellspacing="0" border="0">
<thead>
<tr class="heading">
<th>Item</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
${cartItems.map(item =>
`
<tr>
<td>${item.title}</td>
<td>${item.quantityToSell}</td>
<td>${item.price}</td>
<td>${totalPerItemList(item)}</td>
</tr>
`
)}
</tbody>
<tfoot>
<tr>
<td>
TOTAL:${total}
</td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
`
const htmlToText = require('html-to-text');
const text = htmlToText.fromString(TestTable, {
wordwrap: false,
tables: ['.receipt-box', '.receipt-table']
});
device.open(function(err){
printer
.font('a')
.align('ct')
.style('bu')
.size(1, 1)
.text('Printing Tables Dynamically with epos')
.text('||||||||||||||||||||||||||')
.text(text)
.text('||||||||||||||||||||||||')
.text('========================')
.cut()
.close()
});
the fastest way to do this ive found is to do what ive done in my own project as in
'use strict'
import { app, protocol, BrowserWindow,ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const escpos = require('escpos');
escpos.USB = require('escpos-usb');
const isDevelopment = process.env.NODE_ENV !== 'production'
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
{ scheme: 'app', privileges: { secure: true, standard: true } }
])
async function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
}
})
win.menuBarVisible = false;
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
if (isDevelopment && !process.env.IS_TEST) {
// Install Vue Devtools
try {
await installExtension(VUEJS_DEVTOOLS)
} catch (e) {
console.error('Vue Devtools failed to install:', e.toString())
}
}
createWindow()
})
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === 'win32') {
process.on('message', (data) => {
if (data === 'graceful-exit') {
app.quit()
}
})
} else {
process.on('SIGTERM', () => {
app.quit()
})
}
}
function print(load){
var _message = '';
device.open(function(){
_message = 'done'
printer
.font('a')
.align('ct')
.style('bu')
.size(0.05, 0.05)
.text('Road House Magodo')
.text('Magodo Shopping Arcade Ayodele \r\n Fanoki Magodo Phase I')
.table(['item','qty','total'])
load.load.forEach((element)=>{
return printer.table(element)
})
printer.text(`Total: ${load.total}`)
if(load.change!='card'){
printer.text(`Change: ${load.change}`)
}else{
printer.text('Method: Card')
}
printer.newLine()
printer.newLine()
printer.cut()
printer
.font('a')
.align('ct')
.style('bu')
.size(0.05, 0.05)
.text('Road House Magodo')
.text('Magodo Shopping Arcade Ayodele \r\n Fanoki Magodo Phase I')
.table(['item','qty','total'])
load.load.forEach((element)=>{
return printer.table(element)
})
printer.text(`Total: ${load.total}`)
if(load.change!='card'){
printer.text(`Change: ${load.change}`)
}else{
printer.text('Method: Card')
}
printer.newLine()
printer.newLine()
printer.cut()
printer
.font('a')
.align('ct')
.style('bu')
.size(0.05, 0.05)
.text('Road House Magodo')
.text('Magodo Shopping Arcade Ayodele \r\n Fanoki Magodo Phase I')
.table(['item','qty','total'])
load.load.forEach((element)=>{
return printer.table(element)
})
printer.text(`Total: ${load.total}`)
if(load.change!='card'){
printer.text(`Change: ${load.change}`)
}else{
printer.text('Method: Card')
}
printer.newLine()
printer.cut()
printer.close()
},error=>{
if(error){
console.log(error)
_message = error+'error'
return
}
})
return _message
}
const device = new escpos.USB();
const printer = new escpos.Printer(device);
ipcMain.on('print', (_,load) => {
let _fish =()=>{
return print(JSON.parse(load))
}
_.reply(_fish());
})
basically passing your array or object and looping through it.

converting excel(.xlsx) file to JSON

I have excel sheet called sampledata.xlsx which i converted into json and console.log to print this data.
server.js
var xlsx2json = require('xlsx2json')
xlsx2json(
'sampledata.xlsx',
{
dataStartingRow: 2,
mapping: {
'name': 'B',//name
'sku': 'C',//unit price //sku
'quantity': 'D',//quantity
}
}).then(jsonArray => {
// [
// {"col_1": "Barton LCC", "col_2": "30", "col_3": "86.69"}
// ]
//console.log(jsonArray);
});
with the help of this doc.
What i want to do here is,in my sampledata.xlsx file i have more data like flat,address,price,etc here i already don't know which fields are present in my excel sheet but i want all that to be console.log.How could i do this is there any way to do this.
import xlsx2json from 'xlsx2json';
OR
const xlsx2json = require('xlsx2json');
const excel2json = [
(req, res, next) => {
xlsx2json(req.body.file.path)
.then(result => result[0])
.reduce((object, item, index) => {
if (index === 0) {
object.mapper = item; // eslint-disable-line no-param-reassign
return object;
}
const data = {};
Object.keys(item).forEach((key) => {
data[object.mapper[key]] = item[key];
});
object.data.push(data);
return object;
}, { mapper: {}, data: [] })
.then(excel => console.log(excel)) // this gives json as output
.catch(err => next(err));
},
];
npm install xlsx-to-json-lc --save
npm install xls-to-json-lc --save
var exceltojson = require("xls-to-json-lc");
exceltojson({
input: "pass the input excel file here (.xls format)"
output: "if you want output to be stored in a file"
sheet: "sheetname", // specific sheetname inside excel file (if you have multiple sheets)
lowerCaseHeaders:true //to convert all excel headers to lowr case in json
}, function(err, result) {
if(err) {
console.error(err);
} else {
console.log(result);
//result will contain the overted json data
}
});

Resources