Unable to require node-wit - node.js

I had been using node-wit v3.3.2
Today, I wanted to update and use the latest version.
But I'm unable to import node-wit. Not sure why.
I simply copied the code given in their documentation.
'use strict'
var MY_TOKEN="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
const {Wit, log} = require('node-wit');
const client = new Wit({
accessToken: MY_TOKEN,
actions: {
send(request, response) {
return new Promise(function(resolve, reject) {
console.log(JSON.stringify(response));
return resolve();
});
},
myAction({sessionId, context, text, entities}) {
console.log(Session ${sessionId} received ${text});
console.log(The current context is ${JSON.stringify(context)});
console.log(Wit extracted ${JSON.stringify(entities)});
return Promise.resolve(context);
}
},
logger: new log.Logger(log.DEBUG) // optional
});
The terminal shows this:
const {Wit, log} = require('node-wit');
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3

Could be the node version you are using. You'll need to use the flag --harmony_destructuring when using a lower version.
Taken from: https://github.com/wit-ai/node-wit
# Node.js <= 6.x.x, add the flag --harmony_destructuring
node --harmony_destructuring examples/basic.js <MY_TOKEN>
# Node.js >= v6.x.x
node examples/basic.js <MY_TOKEN>

Related

NodeJS mssql error: SyntaxError: Unexpected token '?'

I'm creating a very basic project with Nodejs for accessing SQL Server database. The steps I take are:
I create the folder for the app ang go into it
I execute "npm init -y"
I execute "npm install mssql"
I copy the short example of the documentation (changing the connetion string values) in index.js:
const sql = require('mssql');
async () => {
try {
await sql.connect('Server=localhost,1433;Database=database;User Id=username;Password=password;Encrypt=true');
const result = await sql.query("select * from mytable");
console.dir(result);
} catch (err) {
console.log(err);
}
};
I execute "node index.js"
Then I get the following error:
C:\Users\User\Desktop\project\app\node_modules\tedious\lib\connection.js:1448
const [, major, minor, build] = /^(\d+)\.(\d+)\.(\d+)/.exec(_package.version) ?? ['0.0.0', '0', '0', '0'];
^
SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (C:\Users\User\Desktop\project\app\node_modules\tedious\lib\tedious.js:59:42)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
What can I do for fixing that and be able to execute the code?

How to bundle worker_thread dependencies with webpack

I'm writing an electron application that uses electron forge for setup and configuration.
The project uses Webpack 5 as a bundler and typescript as the development language. I'm having trouble running a worker_thread on the main-thread.
It all works fine, as long as the worker_thread does not use any imported local modules. But when I import modules they can't be found. I'm thinking this is because webpack doesn't bundle the dependencies from the worker.
My code looks like this:
index.ts (electron main thread):
ipcMain.handle('export', async (event, measurements: Measurement[], options: ExportOptions) => {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./export.worker.js', import.meta.url))
worker.on('message', resolve)
worker.on('error', reject)
worker.postMessage({
measurements,
options,
})
})
})
export.worker.js (same folder as main.ts):
const { parentPort } = require('worker_threads')
const { Export } = require('../preload/export')
parentPort.on('message', async (data) => {
const { measurements, options } = data
await Export.export(measurements, options)
parentPort.close()
})
When I try to run this I get:
Error occurred in handler for 'export': Error: Cannot find module '../preload/export'
Require stack:
- C:\Development\spectro-demo\internal-client\.webpack\main\a3142abb2db60e4fab06.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:892:15)
at Function.Module._load (internal/modules/cjs/loader.js:737:27)
at Module.require (internal/modules/cjs/loader.js:964:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Development\spectro-demo\internal-client\.webpack\main\a3142abb2db60e4fab06.js:2:20)
at Module._compile (internal/modules/cjs/loader.js:1083:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1113:10)
at Module.load (internal/modules/cjs/loader.js:940:32)
at Function.Module._load (internal/modules/cjs/loader.js:781:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\Development\\spectro-demo\\internal-client\\.webpack\\main\\a3142abb2db60e4fab06.js'
]
}
So I'm wondering: How can I use worker_threads that reference modules in my project?
I was able to fix it. Seems to be a bug in webpack 5. See this repo for a workaround: https://github.com/DustinJSilk/web-worker-ts-webpack-test

Azure Chatbot fails with "SyntaxError: Unexpected identifier - cosmosClient.databases.createIfNotExists" while connecting to CosmosDB

I am extremely new to Azure Bot Services and the Azure platform as a whole.
I am trying to create a Chatbot using node.js but I am getting the below error while trying to connect to CosmosDB.
The bot was running fine before I added the below code to connect to CosmosDB.
Any help or guidance on this would be appreciated!
P.S. - I have added the '#azure/cosmos' package and the code runs without any error if I just remove the try-catch segment.
Code for connecting to CosmosDB:
var async=require("async");
var await=require("await");
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
async function readDatabase() {
const { body: databaseDefinition } = await cosmosClient.database(databaseId).read();
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}
Error Message:
Sat Jan 12 2019 03:40:08 GMT+0000 (Coordinated Universal Time): Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
You can't await without being in an async function.
Dump all your code into a async function main(){} method, then call main().catch((err) => console.log(err)); or some similar thing to start the promise and handle errors.
You can see a sample of that kind of pattern here in this sample: https://github.com/Azure/azure-cosmos-js/blob/master/samples/ChangeFeed/app.js#L33
--- EDIT 1 ---
Here's your sample rewritten with Promises:
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
cosmosClient.database(databaseId).read().then(({body: databaseDefinition}) => {
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}).catch((err) {
console.err("Something went wrong" + err);
});
For your sample above, you don't need to import async/await, they are keywords in JavaScript now.
Here's a blog post that compares and contrasts Async/Await and Promises: https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789

Trying to run ripple-lib with node facing syntax error

Trying to run the rippleApi with ripple-lib facing issues like syntaxerror .
Am new to Node and ripple-lib . Please guide me to get rid of this. Thanks in advance
node ripple.js
My Code in ripple.js is
const RippleAPI = require('ripple-lib').RippleAPI;
const Ripple = new RippleAPI({
server: 'wss://s1.ripple.com:443'
});
Ripple.on('error', function (errorCode, errorMessage) {
resp.json('{"status":0,"msg":"Unable to withdraw, problem occured. '+errorMessage+'."}');
});
Ripple.on('connected', function () {
});
Ripple.on('disconnected', function (code) {
console.log('disconnected, code:', code);
});
Ripple.connect().then(function () {
return Ripple.getServerInfo();
}).then(function (server_info) {
var rippleAddress = Ripple.generateAddress();
console.log(rippleAddress);process.exit(-1);
}).catch(console.error);
The Output am getting is
/var/www/html/node_modules/ripple-lib/dist/npm/api.js:83
constructor(options = {}) {
^
SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/www/html/node_modules/ripple-lib/dist/npm/index.js:3:13)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
You need to upgrade nodejs
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

Node.js, Express.js - unexpected token {

My app crashes every time it reaches this line:
const {name, price} = req.query;
^
can't seem to locate the exact answer..here is the error log
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:140:18)
at node.js:1043:3
context:
app.get('/products/add' , (req, res) => {
const {name, price} = req.query;
const INSERT_PRODUCTS_QUERY = `INSERT INTO products (name, price) VALUES ('${ name }', ${ price })`;
connection.query(INSERT_PRODUCTS_QUERY, (err,results) => {
if(err)
{
return res.send(err);
}
else
{
return res.send('succesfully added product');
}
});
});
According to node.green, the object destructuring with primitives syntax works after Node.JS v6.4.0, and throws the Unexpected Token { on Node.js versions below that.
Also, the object rest/spread properties only works out of the box from Node v8.6.0. It works in v8.2.1 with the --harmony flag, and throws the Unexpected Token ... on Node.js versions below that.
You tried to use destructuring assignment. AFAIK its support by nodejs v.6+ from a box and from 4.2.2 with flag --harmony_destructuring

Resources