async await with nodejs 7 - node.js

I've installed nodejs 7.3.0 and I have this code:
let getContent = function (url) {
// return new pending promise
return new Promise((resolve, reject) => {
// select http or https module, depending on reqested url
const lib = url.startsWith('https') ? require('https') : require('http');
const request = lib.get(url, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode));
}
// temporary data holder
const body = [];
// on every content chunk, push it to the data array
response.on('data', (chunk) => body.push(chunk));
// we are done, resolve promise with those joined chunks
response.on('end', () => resolve(body.join('')));
});
// handle connection errors of the request
request.on('error', (err) => reject(err))
})
};
let get = async function (url) {
var content = await getContent(url);
return content;
}
var html = get('https://developer.mozilla.org/it/');
In debug I receive this:
let get = async function (url) {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)

Node 7.3.0 does not support async/await without a feature flag. Spawning node like this should do the trick:
node --harmony-async-await app.js
EDIT
Node now officially supports async/await by default in version 7.6.0, which comes from updating V8, Chromium’s JavaScript engine, to version 5.5.

Related

await dbRef.set({codeVerifier, state}). SyntaxError: await is only valid in async functions and the top level bodies of modules [duplicate]

This question already has answers here:
await is only valid in async function
(14 answers)
Closed 12 months ago.
I am having the following application that should authorize with twitter and i am using Firestore. I am using nodejs and the problem i am having is when i am using await in onRequest that should return a response and the set the values to a firestore database. Below is my code
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const dbRef = admin.firestore().doc("tokens/demo");
const TwitterApi = require("twitter-api-v2").default;
const twitterClient = new TwitterApi({
clientId: "",
clientSecret: "",
});
const callBackUrl = "http://127.0.0.1:5000/lucembot/us-central1/callback";
exports.auth = functions.https.onRequest((request, response) => {
const {url, codeVerifier, state} = twitterClient.generateOAuth2AuthLink(callBackUrl, {
scope: ["tweet.read", "tweet.write", "users.read", "offline.access"],
});
await dbRef.set({codeVerifier, state});
response.redirect(url);
});
exports.callback = functions.https.onRequest((request, response) => {});
exports.tweet = functions.https.onRequest((request, response) => {});
I am getting below error
await dbRef.set({codeVerifier, state});
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1026:15)
at Module._compile (node:internal/modules/cjs/loader:1061:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1151:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Node.js v17.6.0
The top-level await means that you are trying to use async/await syntax outside the async function. You can run the await statement under the async function.
So, you have to write your:
functions.https.onRequest( (request, response) => {
as
functions.https.onRequest( async (request, response) => {
For more details. check here.
Usually await works on functions that return a promise, not on functions that return the request object and expect you to use callbacks or event listeners to know when things are done.
Usually, I would recommend you to use the request-promise module.
But since request-promise has been deprecated, here are other options that don't depend on the NPM request package. got has been mentioned already, but it depends on 11 other packages.
axios, in contrast, only has 1 dependency (for redirects). Everything else is natively implemented and built on top of the native NodeJS packages.
Here is an example using axios:
const axios = require('axios')
const response = await axios.get(callbackUrl)
const result = response.data
or, as a one-liner in JavaScript
const result = (await axios.get(callbackUrl)).data

Running NodeJS App with Socket IO on Shared CPanel server Unexpected token

I created a very simple socket IO app which receives a message and posts it back in a socket group.
The app is running successfully on my Windows machine with Node.js v12.14.0. But I want to get rid of my port forwarding so asked my hoster if it was possible to run the Node.js app on Cpanel. They were not a fan, but opened it up.
I had to install the dependencies manually but finally got no more dependency error while starting the app, but ended up with the error below. After doing some google-ing it probably has to do with the Node.js version on the server which is v6.16.0 . The hoster says they can't get this updated as it comes with cpanel. Now I was hoping there is a way to get my app.js running on this version.
Error:
enter code here[username#server app]$ node /home/username/domains/website.nl/app/app.js
/home/username/domains/website.nl/app/node_modules/ws/lib/websocket.js:347
...options
^^^
SyntaxError: Unexpected token ...
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/username/domains/website.nl/app/node_modules/ws/index.js:3:19)
[username#server app]$ node -v
v6.16.0
The app:
var fs = require('fs');
var https = require('https');
var prvKey = fs.readFileSync('/home/username/ssl/keys/1.key').toString();
var prvCert = fs.readFileSync('/home/username/ssl/certs/1.crt').toString();
var server = https.createServer({key:prvKey,cert:prvCert});
var serverPort = 3000;
// var server = https.createServer();
var io = require('socket.io')(server);
server.listen(serverPort, function() {
console.log('server up and running at %s port', serverPort);
});
io.on("connection", function(socket) {
console.log("user connected: " + socket.id + " - " + socket.request.connection.remoteAddress);
var activequizid = null;
socket.on('jsondata', function(data){
if(data.join.join == "true"){
console.log(socket.id + " join group " + data.join.quizid)
socket.join(data.join.quizid)
}
})
socket.on('jsondataupdate', function(data){
console.log(data.update)
if(data.update.status){
socket.to(data.update.quizid).emit('update', data.update);
}
})
socket.on("disconnect", function(socketd) {
console.log(socketd)
console.log(this.id)
});
socket.on('connection', function () {
console.log('connection!')
})
socket.on('reconnecting', function () {
console.log('reconnecting!')
})
socket.on('reconnect', function () {
console.log('reconnect!')
})
socket.on('disconnect', function () {
console.log('disconnect!')
})
});
console.log("sever online")
websocket.js (partly function with error (look for "...options")) :
send(data, options, cb) {
if (this.readyState === WebSocket.CONNECTING) {
throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
}
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof data === 'number') data = data.toString();
if (this.readyState !== WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
const opts = {
binary: typeof data !== 'string',
mask: !this._isServer,
compress: true,
fin: true,
...options
};
if (!this._extensions[PerMessageDeflate.extensionName]) {
opts.compress = false;
}
this._sender.send(data || EMPTY_BUFFER, opts, cb);
}

SyntaxError: Unexpected token function in async function?

Hi everyone I'm beginner in Nodejs and mongoose.I have tried to insert and retrieve the data in mongoose.I'm using async await function to execute one by one (sequence).can anyone help me? Thanks in advance....
i.e: I want to execute (Async await)concept (SEQUENCE STEP)
1.connect the db
2.create the user
3.find the user.
I'm getting the error :
async function calltaskone(){
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
Code for your reference:
'use strict';
const mongoose=require('mongoose');
const calldbconnect=()=>{
return new Promise((resolve,reject)=>{
if(true){
mongoose.connect('mongodb://vdsd:vdwdwh12dw3,#ds11dwdw.mlab.com:1w5664/vorganisation',{useNewUrlParser:true},(err,db)=>{
if(err){
console.log(err);
reject('Db is not connected');
}
else{
resolve('Db is connected');
}
});
}
});
}
const schemadesign=new mongoose.Schema({
clientName:String,
clientId:Number,
clientAddress:String
});
const modeldata=mongoose.model('clientInfo',schemadesign);
const data=[{
clientName:'VIGNESH Mack',
clientId:4128,
clientAddress:'UK'
},{
clientName:'VIGNESH Tokyo',
clientId:4988,
clientAddress:'USA'
}];
function calldatasave(){
return new Promise((resolve,reject)=>{
modeldata.create(data,(err,a,b)=>{
if(err){
reject(`Error occured while data saved ${err}`);
}
else{
resolve('Data saved successfully');
}
});
});
}
const calldatafind=()=>{
return new Promise((resolve,reject)=>{
if(true){
console.log('try to find');
modeldata.find({'clientId':4988},(err,data)=>{
if(err){
reject(`Error occured while find data: ${err}`)
}
else{
console.log(data);
resolve('Data found');
}
});
}
});
}
async function calltaskone(){
const a=await calldbconnect();
console.log(a);
const b=await calldatasave();
console.log(b);
const c=await calldatafind();
console.log(c);
}
calltaskone();
I believe you're using a older version of Node. Async functions are not supported by Node versions older than version 7.6. You can check here.
If you want to use async/await then you need to transpile using Babel for your node version.
Edit:
As you said you are using v7.3, you can use (from v7.0 to v7.5) the --harmony flag to enable the experimental features. To know more about the flag, check this out: What does `node --harmony` do?

node.js then() not working

I am new to node.js so I am trying to understand promises and wait on node.js. I want to print the file note.txt.
Here is my code
var fs = require('fs');
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));
When I run above code. I get the following error.
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
TypeError: Cannot read property 'then' of undefined
at Object.<anonymous> (/Applications/nodeApps/test/index.js:13:31)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
And I try another method for the same thing.
var fs = require('fs');
async function read_file(){
var file_data = await fs.readFile('note.txt','utf8');
return file_data;
}
console.log(read_file());
And I get following error
Promise { <pending> }
(node:6532) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
I get the same error when I run with --harmony. I m not sure if there is bug on my code or what is wrong. Please help me understand.
My Environment
Node version: v8.9.0
node -p process.versions.v8: 6.1.534.46
You're getting errors because fs.readfile doesn't return a promise; hence then doesn't exist. For you to use the function as a promise, you will need to wrap it up as a promise; you could use something like bluebird or Q.
Thank you for the answers. I learned that function must return promise in order to use then() and catch(). So the code should be like this
var fs = require('fs');
function read_file(){
return new Promise(function(resolve, reject) {
fs.readFile('note.txt','utf8',function(err,file){
if(err){
return reject(err);
}else{
resolve(file);
}
});
});
}
read_file().then(
(data)=>{
console.log('success: '+data);
}
).catch((err)=>{
console.log('error: ',err);
});
If you use NodeJs v10, try fs.promises:
var fs = require('fs').promises; // v10.0 use require('fs/promises')
fs.readFile('note.txt','utf8').then(contents => console.log(contents))
.catch(err => console.error(err));
If not, use readFileSync:
// This code can use for node v10 or lowwer
var fs = require('fs');
var data = fs.readFileSync('a.json');
console.log(data);
try to use the async await
function (async err => {
if (err) {
console.err ....}
await .... <other function included or comes after then .>
await ... <other function included>
})

Calling function depending on updated fields

I want to call different functions depending on the updated model fields.
My code looks like:
update(req, res){
return LED
.findById(req.params.LEDId)
.then(LED => {
if (!LED) {
return res.status(400).send({
message: 'LED Not Found',
});
}
return LED
.update(req.body, {fields: Object.keys(req.body)})
.then(() => res.status(200).send(LED))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
So my plan was to integrate some if-clauses to get the changed value and call some functions depending on the changes.
If-Clauses:
if(req.body.status || LED.status){
BLE.changeStatus(req.body.device_ID,req.body.status);
}else if(req.body.prog || LED.prog){
BLE.changeProg(req.body.device_ID,req.body.prog);
}else if(req.body.white || LED.white){
BLE.changeWhite(req.body.device_ID,req.body.white);
}else if(req.body.color || LED.color){
BLE.changeColor(req.body.device_ID,req.body.color);
}else if(req.body.brightness || LED.brightness){
BLE.changeBrightness(req.body.device_ID,req.body.brightness);
}
Where do I need to integrate these if-clauses that the functions can be called?
I've tried to integrate it in a .then() before I send the field updates to DB but I get the following error while trying to start the server:
SyntaxError: Unexpected token if
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/pi/projekt/server/controllers/index.js:1:75)
[nodemon] app crashed - waiting for file changes before starting...
EDIT
I'm a bit further now..
I've wrote the update function like:
update(req, res){
return LED
.findById(req.params.LEDId)
.then(LED => {
if (!LED) {
return res.status(404).send({
message: 'LED Not Found',
});
}
if(req.body.status){
changeStatus(req.params.LEDId,req.body.status);
console.log('STATUS CHANGED');
} if(req.body.prog){
changeProg(req.params.LEDId,req.body.prog);
console.log('PROG CHANGED');
} if(req.body.white){
changeWhite(req.params.LEDId,req.body.white);
console.log('WHITE CHANGED');
} if(req.body.color){
changeColor(req.params.LEDId,req.body.color);
console.log('COLOR CHANGED');
} if(req.body.brightness){
console.log('BEFORE BRIGHNTESS CHANGED')
changeBrightness(req.params.LEDId,req.body.brightness)
console.log('BRIGHNTESS CHANGED')
}
return LED
.update(req.body, {fields: Object.keys(req.body)})
.then(() => res.status(200).send(LED))
.catch((error) => res.status(400).send(error));
})
.catch((error) => res.status(400).send(error));
},
I've tested it and it jumps to the changeBrightness function. There I want to work with noble. Code looks like this:
changeBrightness(LEDId,updateBrightness){
console.log('BEGINN CHANGEBRIGHTNESS FUNCTION')
var uuid = "4711";
var brightness = updateBrightness;
console.log('BRIGHTNESS', brightness)
console.log('UUID', uuid)
console.log('AFTER CHANGEBRIGHTNESS VAR')
// Connect to client, find Service, find Characteristic and write status
noble.connect(uuid, function(error){
noble.discoverServices([lightningServiceUuid], function(error, service){
var tempLightningService = service[0];
writeFile("SUCCESS -- Discovered Service on UUID");
tempLightningService.discoverCharacteristics([brightnessCharacteristic], function(error, characteristics){
var tempBrightnessCharacteristic = characteristics[0];
writeFile("SUCCESS -- Discovered Characterisitc on UUID");
console.log('IN THE MIDDLE OF CHANGEBRIGHTNESS FUNCTION')
tempBrightnessCharacteristic.write(new Buffer(brightness), true, function(error){
writeFile("SUCCESS -- Wrote brightness characteristic");
});
});
});
});
//Disconnect from client
noble.disconnect(function(error){
writeFile("SUCCESS -- Disconnected from Client");
});
console.log('END CHANGEBRIGHTNESS FUNCTION')
}
I'm currently working with a fake uuid for testing purposes.. So my output looks like this when I start the server and execute a update request:
[nodemon] restarting due to changes...
[nodemon] starting `node ./bin/www`
Executing (default): SELECT "id", "device_id", "name", "group", "status", "device_type", "prog", "white", "color", "brightness", "createdAt", "updatedAt" FROM "LEDs" AS "LED" WHERE "LED"."id" = '1';
BEFORE BRIGHNTESS CHANGED
BEGINN CHANGEBRIGHTNESS FUNCTION
BRIGHTNESS 5
UUID 4711
AFTER CHANGEBRIGHTNESS VAR
PUT /api/led/1 400 357.728 ms - 2
Why does it stop before the noble function? What do I need to change?

Resources