I'm working with node.js, and in one of my js files I'm using const in "strict mode". When trying to run it, I'm getting an error:
SyntaxError: Use of const in strict mode.
What is the best practice to do this?
Edit:
'use strict'
const MAX_IMAGE_SIZE = 1024*1024; // 1 MB
The const and let are part of ECMAScript 2015 (a.k.a. ES6 and Harmony), and was not enabled by default in Node.js 0.10 or 0.12. Since Node.js 4.x, “All shipping [ES2015] features, which V8 considers stable, are turned on by default on Node.js and do NOT require any kind of runtime flag.”. Node.js docs has an overview of what ES2015 features are enabled by default, and which who require a runtime flag. So by upgrading to Node.js 4.x or newer the error should disappear.
To enable some of the ECMAScript 2015 features (including const and let) in Node.js 0.10 and 0.12; start your node program with a harmony flag, otherwise you will get a syntax error. For example:
node --harmony app.js
It all depends on which side your strict js is located. I would recommend using strict mode with const declarations on your server side and start the server with the harmony flag. For the client side, you should use Babel or similar tool to convert ES2015 to ES5, since not all client browsers support the const declarations.
If this is happening in nodejs, it is due to the older version of nodejs. Update node by using,
1) Clear NPM's cache:
sudo npm cache clean -f
2) Install a little helper called 'n'
sudo npm install -g n
3) Install latest stable NodeJS version
sudo n stable
Update nodejs instructions taken from, https://stackoverflow.com/a/19584407/698072
Usually this error occurs when the version of node against which the code is being executed is older than expected. (i.e. 0.12 or older).
if you are using nvm than please ensure that you have the right version of node being used. You can check the compatibility on node.green for const under strict mode
I found a similar issue on another post and posted my answer there in detail
One important step after you update your node is to link your node binary to the latest installed node version
sudo ln -sf /usr/local/n/versions/node/6.0.0/bin/node /usr/bin/node
This is probably not the solution for everyone, but it was for me.
If you are using NVM, you might not have enabled the right version of node for the code you are running. After you reboot, your default version of node changes back to the system default.
Was running into this when working with react-native which had been working fine. Just use nvm to use the right version of node to solve this problem.
Since the time the question was asked, the draft for the const keyword is already a living standard as part of ECMAScript 2015. Also the current version of Node.js supports const declarations without the --harmony flag.
With the above said you can now run node app.js, with app.js:
'use strict';
const MB = 1024 * 1024;
...
getting both the syntax sugar and the benefits of strict mode.
I had a similar issue recently and ended up in this Q&A. This is not the solution the OP was looking for but may help others with a similar issue.
I'm using PM2 to run a project and in a given staging server I had a really old version of Node, NPM and PM2. I updated everything, however, I kept keeping the same error:
SyntaxError: Use of const in strict mode.
I tried to stop and start the application several times. Also tried to update everything again. Nothing worked. Until I noticed a warning when I ran pm2 start:
>>>> In-memory PM2 is out-of-date, do:
>>>> $ pm2 update
In memory PM2 version: 0.15.10
Local PM2 version: 3.2.9
Gotcha! After running pm2 update, I finally was able to get the application running as expected. No "const in strict mode" errors anymore.
I was using pm2 to start and maintain the node processes.
From the CLI it worked perfectly.
which node
/usr/local/bin/node
node -v
v10.15.0
However, I set up a cronjob and I got the syntax error.
Then wrote a cronjob to check which node and node -v and surprisingly, it was a different path and version.
which node
/usr/bin/node
node -v
v0.10.48
To fix the cronjob I had to use the flag --interpreter for pm2, like so:
pm2 start dist/server.js --interpreter=/usr/local/bin/node
The use of const in strict mode is available with the release of Chrome 41.
Currently, Chrome 41 Beta is already released and supports it.
cd /
npm install -g nave
nave use 6.11.1
node app.js
const is not supported by ECMAScript. So after you specify strict mode, you get syntax error. You need to use var instead of const if you want your code to be compatible with all browsers. I know, not the ideal solution, but it is what it is. There are ways to create read-only properties in JavaScript (see Can Read-Only Properties be Implemented in Pure JavaScript?) but I think it might be overkill depending on your scenario.
Below is browser compatibility note from MDN:
Browser compatibility
The current implementation of const is a Mozilla-specific extension
and is not part of ECMAScript 5. It is supported in Firefox & Chrome
(V8). As of Safari 5.1.7 and Opera 12.00, if you define a variable
with const in these browsers, you can still change its value later. It
is not supported in Internet Explorer 6-10, but is included in
Internet Explorer 11. The const keyword currently declares the
constant in the function scope (like variables declared with var).
Firefox, at least since version 13, throws a TypeError if you
redeclare a constant. None of the major browsers produce any notices
or errors if you assign another value to a constant. The return value
of such an operation is that of the new value assigned, but the
reassignment is unsuccessful only in Firefox and Chrome (at least
since version 20).
const is going to be defined by ECMAScript 6, but with different
semantics. Similar to variables declared with the let statement,
constants declared with const will be block-scoped.
Related
i want to install newrelic on my project but i'm receiving from de console:
node_modules\#newrelic\native-metrics\build\bind ing.sln.metaproj : error MSB4057: The target "/t:native_metrics" does not exist in the project.
in another machine works perfectly. i really would appreciate if some one could help with that, i already tried this from newrelic https://discuss.newrelic.com/t/newrelic-native-metrics-does-not-install-on-windows-10-from-corrupt-vcxproj/54625/3
This is most likely due to the version of node-gyp. A change was introduced into node-gyp
version 3.7.0 that prepends /t: to the build target on Windows machines. The ./lib/pre-build.js file that New Relic uses to bootstrap the build also prepends /t: to the target which results in a value of /t:/t:native_metrics being passed to MSBuild, which isn't valid. You can fix this by installing an older version of node-gyp. Depending on how npm is set up on your machine you may also have to set the npm_config_node_gyp environment variable to the path of the older version of node-gyp so it gets picked up by the New Relic bootstrapper.
The Wekan code that be built by Meteor cannot run in node 0.10.4x ,
Meteor will create the code for new version node, like const or lambda expression.
How to ask Meteor to build the code that can be run in node 0.10.4x ?
Error 1:
/home/wekan/output/bundle/programs/server/packages/modules.js:33433
const Boom = require(‘boom’);
^^^^^
SyntaxError: Use of const in strict mode.
at /home/wekan/output/bundle/programs/server/boot.js:292:30
at Array.forEach (native)
at Function..each..forEach (/home/wekan/output/bundle/programs/server/node_modules/underscore/underscore.js:79:11)
at /home/wekan/output/bundle/programs/server/boot.js:133:
Error 2:
/home/wekan/output/bundle/programs/server/packages/modules.js:33571
credentialsFunc(attributes.id, (err, credentials) => {
^Preformatted text
SyntaxError: Unexpected token >
at /home/wekan/output/bundle/programs/server/boot.js:292:30
at Array.forEach (native)
at Function..each..forEach (/home/wekan/output/bundle/programs/server/node_modules/underscore/underscore.js:79:11)
at /home/wekan/output/bundle/programs/server/boot.js:133:5
According to the Wekan documentation at https://github.com/wekan/wekan/wiki/Install-and-Update
If you haven't already, you need to install Node.js, given that we
need node version 4.8.4, make sure to either use the custom packages
(the ones of your OS are likely too old) or install the correct
version from the Node.js website.
Node 0.10.4 is pretty old already, I don't know why you are still using it. You can use something like nvm if you want to manage different versions of node on your machine.
It seems, you're using really old version of wekan that needs such old version of node.
Unfortunately, babel transpiler (Meteor is using it to transpile JS code) has dropped support for Node 0.10 and 0.12 (discussed here).
I'd suggest you to update your wekan version or use nvm to install and use different version of node simultaneously.
Using Win10 Pro / VS2015 with a 'website' project (not asp.net, basic website)
When attempt to save/reload gulpfile.js I receive the error message (from Task Runner Explorer/output)
SyntaxError: Use of const in strict mode.
In the present case it is choking on 'gulp-changed'
I have looked through the answers and comments available:
SyntaxError: Use of const in strict mode
SyntaxError: Use of const in strict mode?
I have updated my version of node to the latest: 6.10.30
I have cleaned the cache (npm cache clean -f)
I have used 'which node' to determine that node is pointing to the installation of the latest install.
"n" does not want to install on Windows (?)
In my case the environment path, $(PATH) already include the global install of node but I needed to move it ahead of the $(DevEnvDir) paths so that it would get priority.
(added after correct answer provided, thanks #baao)
VS seems to install (and then use) an old version of node, which is why the task runner is breaking the build.
Go to Tools > Options > Projects and Solutions > External Web Tools and add the correct path to your node version (find the path with which node).
Credits to: https://github.com/sindresorhus/gulp-imagemin/issues/178#issuecomment-218131138
Is there a way to get ES6 in sails.js?
SailsJS is just a framework written via ES5 syntax and it doesn't need to support ES6.
You can write project with ES6 syntax as you usually do and use Babel\Traceur\whatever for running.
My flow is following:
Create Sails project;
Install babel as devDependencies;
Update npm start script in package.json with "start": "babel-node app.js";
That's it. I can write ES6\7 code in my controllers\models\etc and run the server via npm start command. It works as usual as you wrote it with ES5 syntax.
Babel Transpiler
Babel Node
You need to check compatibility of ES6 with node.js instead any framework like sails.js, express etc.
Because at last node.js will change the javaScript to server side code.
So it doesn't matter which framework you are using.
You can use the sails with ES6:
For ES6 compatibility check kangax.github.io.
Recommended :
Sails v 0.11.0 or greater
Node v 4.. or greater
npm v 2.14.4 or greater
Now you are ready to explore new Ecmascript6 feature.
You will get the new feature from http://es6-features.org/.
TEST :
Code:
ecma6Test:function(req,res,next){
var evens =req.body.evens
odds = evens.map(v => v + 1);
res.json({sucess:true,'odds':odds});
}
Request:
{"evens":[2,4,6,8,10]}
Response :
{
"sucess": true,
"odds":[3, 5, 7, 9, 11]
}
This is a node.js question not specifically sails. Yes current version of node.js support certain ES2015 standards depending on your Node.js version and flags you use when you start your server.
Most features are already active, however to use all features, you would use node app.js --es_staging or node app.js --harmony in your project folder instead of sails lift
The following link provides updated information on what features current version of Node support and how to access them.
https://nodejs.org/en/docs/es6/
Vishnu's answer has you covered.
The explicit list of ES6 features available in the latest node release is here https://nodejs.org/en/docs/es6/
Which ES6 features ship with Node.js by default (no runtime flag required)?
let (strict mode only)
const
function-in-blocks (strict mode only)
As of v8 3.31.74.1, block-scoped declarations are intentionally implemented with a non-compliant limitation to strict mode code. Developers should be aware that this will change as v8 continues towards ES6 specification compliance.
Classes (strict mode only)
Collections
Map
WeakMap
Set
WeakSet
Typed arrays
Generators
Binary and Octal literals
Object literal extensions (shorthand properties and methods)
Promises
New String methods
Symbols
Template strings
Arrow Functions
There is the sails-hook-babel hook that might work out for you. It doesn't work for me, as I explain below, but I hope it gets higher visibility, is improved, and then this answer will be more relevant.
Currently, as of v6.0.1 the library will work for files loaded after the sails hooks run. This means that if you want to use ES2015 in e.g. your config/routes.js file, you will get a syntax error. But as suggested in this issue, it should work for e.g. files in the api folder.
I'm trying to run node.js backend server. I've received error unexpected reserved word on import in Node.js file.
The lines in file core.module.js is:
'use strict';
import lodashMixins from './lodashMixins.js'
... other imports and configurations ...
I launch simple command: node core.module.js
It's not uncommon error, but usually it happens with other libraries. I haven't seen solution for Node.js. How should I fix this? I'm using Windows Server.
Edit: I've find out that it's ES6, but how could I launch it? It looks like backend for the application, but I have no idea what command should I use to launch it without errors.
import is a part of ECMAScript 2015 (ES6) standard and as Amit above mentioned it is not currently implemented natively in Nodejs.
So you can use transpiler like babel to run your es6 script
npm install babel
An example based on this answer
app.js
import {helloworld,printName} from './es6'
helloworld();
printName("John");
es6.js
module.exports = {
helloworld: function() { console.log('hello world!'); },
printName: function(name) { console.log(name); }
}
And using require hook in start.js
require("babel/register");
var app = require("./app.js");
And start your app as
node start.js
EDIT
The above answer was base on babel v5.8.23. For babel >= v6
Use require hook in start.js as
require('babel-core/register');
require("./app.js");
Also, transformations are not enabled by default. So you will need to install a preset. In this case use es2015
npm install babel-preset-es2015
And use it in a .babelrc file in root folder
{
"presets": ["es2015"]
}
The import keyword is part of the modules feature in ECMAScript 2015, along with export and a few other specifications.
It is currently not implemented natively in NodeJS, even on the lastest version (v0.12.7), nor is it supported in the ES2015 "friendlier" fork iojs.
You will need to use a transpiler to get that to work.
[edit] it's still unsupported in the latest version (v5.8) despite the existence of an --harmony_modules flag, which does nothing. Your best run is to use babel, as explained here and here
I ran into this issue as I manually install any of these tools outside of Visual Studio. But Visual Studio ships with multiple open source command line tools that are used in modern web development workflows. Here’s how you can tell Visual Studio to use the same version that you have manually installed
Go to Tools –> Options –> Projects and Solutions –> External Web Tools
Set the global PATH environment variable before the internal path, you can just use the arrows at the top-right to change the order.
or
First, find the Node.js installation you already have and use at the command line. By default, Node.js 0.12.7 installs to “C:\Program Files\nodejs”. Add this entry at the top to the path to the node.js directory to force Visual Studio to use that version instead
This may not be the official answer, but I stumbled here after searching around for the 'unexpected reserved word'. After poking around, I discovered my problem was that, in fact, I just needed to run an npm install after having updated my branch from origin / rebasing. Hope this helps someone else who is furiously reverting their code trying to figure out what they broke! :)