(Tutorial) Script does not run due SyntaxError: Block-scoped declarations - javascript

As per Quill's suggestion, I am posting this again. The first time I posted "npm update node" fixed the problem.
I bought a tutorial from Packtpub.com called "Web Development with NodeJs and MongoDB" and I want to run the sample tutorial code. Here is an example:
#!/usr/bin/env node
console.log('Argument vector');
console.log(process.argv);
let args = process.argv.slice(2);
console.log('\nArguments after slicing');
console.log(args);
let name = args[0];
if (!name) {
throw Error('\nYou have not given your name, bye');
}
console.log('\nHello ' + name);
So I download and install Node-v5.6.0-x64.msi. Why do I get errors when I use the let command:
-*- mode: compilation; default-directory: "c:/Users/v-sihein/Documents/books/2016/javascript/Web Development with Node.JS and MongoDB/3413OS_Section 01_Code/1/1.3/" -*-
Compilation started at Sat Feb 13 16:25:01
node 03-hello-arguments.js siegfried
c:\Users\v-sihein\Documents\books\2016\javascript\Web Development with Node.JS and MongoDB\3413OS_Section 01_Code\1\1.3\03-hello-arguments.js:9
let args = process.argv.slice(2);
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3
Compilation exited abnormally with code 1 at Sat Feb 13 16:25:01
Now if I change the "let"s to "var"s then it works!
I had this problem previously (a couple of days ago) and "npm update node" fixed the problem (I think -- maybe I mistakenly ran the version with the "var" instead of the "let"). However, I have since reinstalled windows 10 and now "npm update node" does not fix the problem any more.
So what versions of javascript and ecmascript can I expect to be able to execute with node v5.6.0? I've been boogle searching and I cannot find a simple table of javascript features for the different versions of node and javascript. I would think knowing what versions of javascript/ecmascript is supported by a version node would be very basic/important information to every node programmer! Can someone point me to such a table?
Did I buy a bad tutorial? I think the author uses linux or MAC and I'm using windows. Should not node work the same way on mac/linux and windows?
Please tell me if this program works for you on your computer. Be sure to mention if you are running mac, unix, linux or windows (or something else?).
Thanks
Siegfried

You should just add 'use strict' to the beginning of the js part
#!/usr/bin/env node
'use strict'
(...)
This will then immediately work. It's weird that the tutorial doesn't mention that.

Related

How do I get 'onoff' working on a Raspberry Pi 4B?

I am trying to make a 'Coocking-aid'. I am using a Raspberry Pi 4B with the official 7" touchscreen and an active piezo buzzer. The 'program' should run in Chromium (the RPi's webbrowser) and I write it in HTML, CSS and Javascript. I can do some tricks in Javascript but lack a lot of knowledge there. I try to sound the buzzer with Javascript, but so far without success.
The buzzer is connected between GPIO-pin 17 and Ground (connector-pins 11 and 9). When GPIO 17 is made high (+3V) the buzzer will sound.
I have tested this 'circuit' with a small Python program, which successfully turned the buzzer on:
1. from gpiozero import Buzzer
2. buzzer = Buzzer(17)
3. buzzer.on()
To do the same with Javascript I learned that I needed to install Node.js and its module 'onoff'.
From this web-post 1 I learned how to install node.js, by typing the following commands in the terminal:
curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -
sudo apt install -y nodejs
I checked the installation by typing: "node -v". The response was: "v15.12.0"
I also checked the version of Node's package manager by typing: "npm -v". The response was: "7.7.5"
From this web-post 2 I learned how to install "onoff" by typing the following command in the terminal:
npm install onoff
I checked the installation by typing: "node -v". The response was "v15.12.0"
In the RPi directory "/home/pi/node_modules/onoff/examples" is a file called: "blink-led.js"
which I used as an example to create (in the same directory) a file called: "test.js" with the following code:
'use strict';
const Gpio = require('../onoff').Gpio; // Gpio class
const buzzer = new Gpio(17, 'out'); // Export GPIO17 as an output
buzzer.writeSync(17); // Make GPIO-pin 17 high
In the terminaI I moved to the same directory by typing:
cd /home/pi/node_modules/onoff/examples
and then executed "test.js" file by typing:
node test.js
Unfortunately the buzzer was not activated and a comprehensive error message was shown (see under).
I get the impression that the numbers are program line numbers and I had a look here and there, but I can't figure out what is wrong.
Any help would be much appreciated!.
The error message was:
/home/pi/node_modules/bindings/bindings.js:121
throw e;
^
Error: libnode.so.64: cannot open shared object file: No such file or directory
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1151:18)
at Module.load (node:internal/modules/cjs/loader:972:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:996:19)
at require (node:internal/modules/cjs/helpers:92:18)
at bindings (/home/pi/node_modules/bindings/bindings.js:112:48)
at /home/pi/node_modules/epoll/epoll.js:7:31
at Object.<anonymous> (/home/pi/node_modules/epoll/epoll.js:15:3)
at Module._compile (node:internal/modules/cjs/loader:1092:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10) {
code: 'ERR_DLOPEN_FAILED'
}

SyntaxError: Unexpected token, Worked on Windows but not on the VPS, Any Ideas? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Issues:
I recently moved my code from a Windows machine to a VPS, everything seemed to be working on my PC, but when I moved to the VPS, I got the following error
/root/node_modules/discord.js/src/client/Client.js:41
} catch {
^
SyntaxError: Unexpected token {
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/root/node_modules/discord.js/src/index.js:8:11)
Environment Details:
I am using Cloud Computing on Ubuntu 18.04 64x
I am using the command handler found here: https://anidiots.guide/first-bot/a-basic-command-handler
Any and all help will be greatly appreciated
Seeing as this question is currently locked, and not accepting new answers, I thought I would address a few observations on the incompatibilities between node versions, all due credit goes to the commenters: #tipakA and #Christian.
There are incompatibilities between versions of Node, it may simply be that you need to update your VPS's version of Node to a later version, one where the catch blocks are optional, or more precisely to one which satifies your dependancies, in light of the comment by #tipakA
v12 of discord.js indeed requried node 12 or newer - #tipakA
In addition to simply upgrading to a compatible version of Node, I would also suggest, you "preserve" the node version as a dependency in your package.json file, like:
"engines" : {
"node" : ">=0.12"
}
Ensure you, signal that your project will not work at all in lower versions of Node, with this flag
"engineStrict" : true
Now when you deploy and npm install, you will be warned of any discrepancies in Node versions.
Unfortunately it appears that support for "engines" is in flux between npm versions, for example they are deprecated, as of npm 3, but supported in npm v 5x..., so you may want to 'patch/polly-fill' the feature, as outlined in this article, all credit goes to 'Adam Bisek' the author of that article.
Also, this answer on StackOverflow, provides additional approaches to the Node version as dependency issue.
Alternatively, without having more insight into the stack, or the environment, I have to go with what looks obvious to me.
From the fact that this is throwing a SyntaxError I would look at where the SyntaxError is. To me the signature of your try catch looks off.
JavaScript has the following signature for a Try/Catch block:
try {
try_statements
}
[catch (exception_var_1 if condition_1) { // non-standard
catch_statements_1
}]
...
[catch (exception_var_2) {
catch_statements_2
}]
[finally {
finally_statements
}]
So you would need to have a try catch as such, like this
try {
// attempt to perform something here...
} catch ( e ) {
// do something with "e" or handle the error some how.
}
you can read up on this more here.

Syntax error at new Script (vm.js:51:7) whilst running code for a discord bot in javascript

I get an error whilst running my node index.js
here is my code
const botconfig = require("./botconfig.json");
const Discord = require("discord.js");
const bot = new Discord.Client({disableEveryone: true});
bot.on("ready", async () => {
console.log(`${bot.user.username} is online!`);
}};
bot.login(botconfig.token);
here is my error message
SyntaxError: missing ) after argument list
at new Script (vm.js:51:7)
at createScript (vm.js:138:10)
at Object.runInThisContext (vm.js:199:10)
at Module._compile (module.js:624:28)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:190:16)
hope you can help!
If you see an error at new Script (vm.js:51:7), it means there's an error in a custom script that you passed to vm.js, the Node module that communicates with the V8 Virtual Machine.
new Script in vm.js is simply evaluating your code.
So you need to work out what the fault is in the code you passed to the V8 virtual machine. If you run the file directly (e.g. node some/path/some_file.js) you should get a pointer to the actual fault that looks like this:
YourPC:your-directory you$ node some/path/some_file.js
/some/system/path/your-directory./some/path/some_file.js:123
}};
^
SyntaxError: missing ) after argument list
at new Script (vm.js:51:7)
at createScript (vm.js:138:10)
at Object.runInThisContext (vm.js:199:10)
The part above the error message with the ^ caret shows you the faulty point in your own code.
In your case, it's pretty easy to spot: you have a }}; that should be a });.
If you have code that seems 100% fine but encounters this error, like #maevanapcontact's failing arrow functions, maybe you're using an old version of Node with an old version of V8 that didn't support that ECMAScript feature. Arrow functions didn't have complete support until Node version 6.
I had the same error as you and I have fixed it by using function(){}; instead of () =>.
I don't really know why it doesn't work with arrow functions, but it did the job for me like that.
I found it helpful to add a break-point in vm.js where the error is thrown. (click on the filename link in the stack trace).
Reload the page and then inspect the local variables.
The filename variable will give the the full name of the js file that caused the error.
Unfortunately this isn't enough to narrow down the exact line, so I ended up deleting parts of the file until it would compile. From there I was able to narrow what was causing the error. In my case, my IDE linter wasn't giving me any hints either.
The following helped me.
Delete all node_modules
rm -rf node_modules/
and then install
npm install

Playing a local file on RPi with Node.js

I have a Raspberry Pi set up with a Node.js app that responds when it sees button push from an Amazon Dash Button. It was originally supposed to be a silent doorbell from https://github.com/initialstate/silent-doorbell, but I would like to just have it play a local sound file. Which I think should be easy enough, but my inexperience with coding leaves me just trying new stuff that I find all over the internet.
I can play the file from the terminal with the following and it plays just fine:
$ omxplayer example.mp3
But, no matter how I try to put it in the Node.js app and trigger when the Dash Button is pressed it won't work.
var dash_button = require('node-dash-button'),
dash = dash_button('XX:XX:XX:XX:XX:XX'), //REPLACE WITH YOUR ADDRESS
exec = require('child_process').exec;
Omx = require('node-omxplayer');
player = Omx('~/node_modules/node-dash-button/example.mp3');
let spawn = require('child_process').spawn;
dash.on('detected', function() {
console.log('Button pushed!');
player.play();
});
When run with my latest as above, I get this:
/home/pi/node_modules/node-dash-button/doorbell.js:7
let spawn = require('child_process').spawn;
^^^^^
SyntaxError: Unexpected identifier
at exports.runInThisContext (vm.js:73:16)
at Module._compile (module.js:443:25)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
After upgrading Node.js to the newest version as suggested by #Quentin using the Major Version Upgrade directions on this site http://thisdavej.com/upgrading-to-more-recent-versions-of-node-js-on-the-raspberry-pi/ I was able to get past this. Now I can't get past how to properly use omxplayer. When running the same code as above after the Node.js upgrade I now get this error after pressing the Amazon Dash button which then crashes the app:
pi#raspberrypi:~/node_modules/node-dash-button $ sudo node doorbell.js
Button pushed!
/home/pi/node_modules/node-omxplayer/index.js:103
throw new Error('Player is closed.');
^
Error: Player is closed.
at writeStdin (/home/pi/node_modules/node-omxplayer/index.js:103:10)
at EventEmitter.Omx.omxplayer.play (/home/pi/node_modules/node-omxplayer/index.js:133:27)
at Readable.<anonymous> (/home/pi/node_modules/node-dash-button/doorbell.js:13:12)
at emitOne (events.js:96:13)
at Readable.emit (events.js:188:7)
at PcapSession.<anonymous> (/home/pi/node_modules/node-dash-button/index.js:87:28)
at emitOne (events.js:96:13)
at PcapSession.emit (events.js:188:7)
at PcapSession.on_packet_ready (/home/pi/node_modules/node-dash-button/node_modules/pcap/pcap.js:99:10)
at packet_ready (/home/pi/node_modules/node-dash-button/node_modules/pcap/pcap.js:44:14)
I tried a few different things to try and get the player to spawn with no luck. The index.js file referenced mentions to use the player.running command but I still get the player is closed error when attempting to use this.
You are using a version of Node older than the 4.x series.
Consequently it sees let as an identifier rather than the keyword, so it doesn't expect it to be immediately followed by another identifier (spawn).
Upgrade your installation of Node to a current version.
Alternatively, use a different variable declaration, such as var.

Get error with "line.slice()" on "karma init"

I was started to read "Developing an AngularJS Edge", and I wanted to set up the various frameworks in use.
The book uses nodejs and karma, along with several other frameworks.
I'm on Win7x32.
I just upgraded my nodejs to the latest, v0.10.18 .
I installed the Karma package with "npm install -g karma". This appeared to complete successfully.
I then ran "karma init", which did this:
% karma init
>
readline.js:507
this.line = this.line.slice(this.cursor);
^
TypeError: Cannot call method 'slice' of undefined
at Interface._deleteLineLeft (readline.js:507:25)
at suggestNextOption (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:167:9)
at nextQuestion (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:235:12)
at process (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:250:10)
at Object.exports.init (C:\Users\David\AppData\Roaming\npm\node_modules\karma\lib\init.js:352:6)
at Object.<anonymous> (C:\Users\David\AppData\Roaming\npm\node_modules\karma\bin\karma:25:37)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
Note that this error is virtually identical to the stack trace reported by this person a month ago, but that report has received no response.
Probably you're using the Git Bash terminal, MinTTY, which doesn't have full support for TTY.
You have 4 options to fix the problem:
Use CMD terminal with the Windows shell (the default Windows console)
Use CMD terminal with the Bash shell (execute "C:\Program Files\Git\bin\bash.exe" --login -i in cmd terminal)
Use Powershell (an alternative terminal typically installed by default in Windows environments)
Use an alternative terminal (or develop a new one :stuck_out_tongue_winking_eye: )
If you just need execute isolated interactive commands like karma init, I recommend option 1 for it and then come back to Git Bash. However I would give a try to Powershell.
The reason for the error with running npm in Cygwin seems to be a known issue with npm. You can use the work around mentioned here,
https://stackoverflow.com/a/22436199/2390020
Faced the same issue.try this
node node_modules/karma/bin/karma init
I got the same error with MINGW64.
Runs properly on default command prompt.
One other likely relevant point that I failed to mention is that I was running these commands from a Cygwin rxvt window.
I just tried completely uninstalling nodejs and reinstalling it.
When I brought up the rxvt window again and ran "npm install -g karma", it failed with the following:
/c/Program Files/nodejs/npm: line 2: $'\r': command not found
/c/Program Files/nodejs/npm: line 4: $'\r': command not found
/c/Program Files/nodejs/npm: line 5: syntax error near unexpected token `$'in\r''
'c/Program Files/nodejs/npm: line 5: `case `uname` in
That led me to search for that error on the web, and I found this thread, which implies that it simply doesn't support Cygwin (unfortunate, but not a huge problem).
When I then brought up a plain, ugly, unfriendly "cmd" window, both the karma installation and "karma init" completed successfully (or at least it gave me the first question in the "init" process).
In my case, the problem was that I was using the git bash terminal in windows. When I ran the command in a cmd window it worked fine.
Run the command in github shell command window. Worked for me.
If you open up the karma file it's just a node script, so an alternative way of executing it would be:
node karma init
This worked for me in the MINGW64/git bash shell

Categories