ES6 import statements not working in Node v8.4.0 - node.js

I'm using the latest version of Node.js that is v8.4.0. However, in the import and export statements, I'm getting errors:
import express from 'express';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:537:28)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3
What Node.js version should I install in order to work these ES6 codes?
OS - Ubuntu 17.04
node -v: v8.4.0
npm -v: 5.3.0

One way that I have worked around this issue...
Install babel stuff for the project:
$ npm install babel-register babel-preset-es2015 --save-dev
Create an index.js file that is the main entry point into the app:
// index.js
// by requiring `babel/register`, all of our successive `require`s will be Babel'd
require('babel-register')({
presets: [ 'es2015' ]
});
require('./server');
Then, create a file called server.js that will have your normal index code:
// server.js
import express from 'express';
var app = express()
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(3000, () => console.log('Example app listening on port 3000!'))
And run:
$ node index.js

const express = require('express');
is the right syntax as some es6 features ie import express from express is currently not available with node!

Related

Node package 'node-fetch' SyntaxError: Unexpected identifier

I have a problem. I am trying to run my NodeJS script using the command:
node /var/script/NodeJS/test.js
But when I run it, I get the following error:
/var/script/NodeJS/node_modules/node-fetch/src/index.js:9
import http from 'http';
^^^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/var/script/NodeJS/test.js:2:15)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
I have already run the following commands in the terminal:
cd /var/script/NodeJS
npm install
npm install http
npm install node-fetch
I am running node version: v10.19.0
Here is the code I have that gives the error:
const express = require("express");
const fetch = require('node-fetch');
const app = express();
const PORT = process.env.PORT = 8787;
let router = express.Router();
It's just the imports, but this code already gives the provided error!
I can see both the modules in the node_module folder, so why am I getting this error and how can I fix this?
This can happen if you use a 3.X version of node-fetch and a Node version less than 12.20.0
Because node-fetch from v3 is an ESM-only module.
According to the documents you must install a version 2.X or less
npm install node-fetch#2
rename file extension from .js to .mjs
filename must be: test.mjs
import fetch from 'node-fetch';
const express = require("express");
const app = express();
let router = express.Router();
const PORT = process.env.PORT = 8787;
also keep in mind node-fetch has requriements on node version:
https://github.com/node-fetch/node-fetch/blob/main/package.json#L14
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
run it as: node test.mjs
Bonus: If You don't like to use mjs and etc try to install node-fetch#2.6.5
npm i --save node-fetch#2.6.5

OKTA express middleware - TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type Function. Received type undefined

Just including the following in an app causes the following error.
const { ExpressOIDC } = require('#okta/oidc-middleware');
Full error:
$ node app.js
internal/util.js:257
throw new ERR_INVALID_ARG_TYPE('original', 'Function', original);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "original" argument must be of type Function. Received type undefined
at promisify (internal/util.js:257:11)
at Object.<anonymous> (/dev/tmpOidc/node_modules/jose/lib/jwk/key/rsa.js:13:25)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> (/dev/tmpOidc/node_modules/jose/lib/jwk/import.js:9:16)
Steps to reproduce
1. Create a new node app and add express and Okta's oidc middleware
npm init
npm install express --save
npm install --save #okta/oidc-middleware
Create app.js
const express = require('express')
const app = express()
const port = 3000
// const { ExpressOIDC } = require('#okta/oidc-middleware');
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
Run it
node app.js
See how it runs. Finally, uncomment and include the line that sets up the OIDC middleware.
const { ExpressOIDC } = require('#okta/oidc-middleware');
Run the app again and I get the error above shows up.
Solved: Need to run with node v12 not v10
I just published a YouTube video that shows you how to use Okta's OIDC Middleware.
You can find the steps I used here. To summarize:
Create a new project with express-generator and pug: npx express-generator --view=pug
Add a new web app on Okta with http://localhost:3000/callback as the login redirect URI
Install Schematics CLI: npm install -g #angular-devkit/schematics-cli
Install and run OktaDev Schematics with your Okta values:
npm i #oktadev/schematics
schematics #oktadev/schematics:add-auth --issuer=$issuer --clientId=$clientId --
clientSecret=$clientSecret
Start your app and authenticate with Okta: npm start
You can see the result of these steps in this GitHub repo.
Solved. When I posted my question I should've included system information such as the version of Node. I had v10.8.0. Once I updated to v12 the typeerror went away.

NodeJs Npm Start works but node index.js doesn't. SyntaxError: Unexpected identifier

I have an app in NodeJS with Apollo Server, Graphql, etc. I want to use PM2 to have my index like a service so, when I close the console It dont stop.
When I execute npm start the server starts perfect. This is my start in package.json
"start": "nodemon ./index.js --exec babel-node -e js",
If I execute node index.js then this error appears.
/home/ubuntu/react/desafio/servidor/index.js:1
import express from 'express';
^^^^^^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
this is my index.js code
import express from 'express';
import { ApolloServer, AuthenticationError } from 'apollo-server-express';
import { typeDefs } from './data/schema';
import { resolvers } from './data/resolvers';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
import db from "./models";
dotenv.config({path:'variables.env'});
const cors = require('cors');
const app = express();
// enable cors
// app.use(cors());
const addToken = async (req) =>{
}
const server= new ApolloServer({
typeDefs,
resolvers
});
server.applyMiddleware({app});
app.listen({port:9000},()=> console.log(`Server Corriendo http://localhost:9000${server.graphqlPath}`));
what Im doing wrong?
node index.js will throw an error because your code is in ES6, to successfully run your code you will have to run it with babel-node which will compile it to ES5. babel-node comes with the babel-cli which you have to install.
" ./index.js --exec babel-node -e js" exactly does this which is to compile ES6 to ES5
Babel helps to turn our codes from ES6 to ES5. There are some ES6
features that our browsers and node are yet to understand, and older
browsers do not understand ES6 codes, so we use babel to compile our
code to ES5 so that both old browsers and new browsers can understand.
While import is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.
check this node import vs require
in node 9 ** it is enabled behind a flag, and uses the .mjs extension**
node --experimental-modules my-app.mjs
you can use require statements:
const express = require("express");
If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel

Error: Cannot find module 'express' when running on Azure

I have a node.js app which uses express and runs locally with no problems. However, on Azure I am seeing:
Application has thrown an uncaught exception and is terminated:
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\home\site\wwwroot\server.js:1:79)
at Module._compile (module.js:570:32)
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)
The packages.json file contains the dependency:
"express": "^4.15.3"
Assuming something had gone wrong with the npm install, I went to the Kudu remote execution console and ran npm outdated. No packages are missing.
This is my server.js file:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.port || 8000;
app.use(bodyParser.urlencoded({ extended: true }));
require('./app/routes')(app);
app.listen(port, () => {
});
I'm assuming it is something very obvious, but I can't work out what I'm missing.
Assuming your Azure App Service is Windows environment, try to include node_modules in the wwwroot.
There isn't much we can really help with here, as the error you have provided indicates that the express npm package has not been installed properly. So, I would suggest that you use App Service Editor (https://[YouAppName].scm.azurewebsites.net/dev/wwwroot/) to troubleshoot this issue by checking whether the express folder exists in the node_module.
You can also run command npm install in the console, restart your app and run it (Ctrl + F5) in the browser.

node server.js not responding error message

I am working on a project that requires the use of node server.js file. The documentation for the project states to type in 'node server.js' in terminal to start the server, but when I do that I'm receiving an error cannot find module 'express'.
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:455:15)
at Function.Module._load (module.js:403:25)
at Module.require (module.js:483:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/.../Desktop/react/react-app-project/server.js:6:15)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
This is the code in server.js
var express = require('express');
var app = express();
/*
this says: serve all the files in the src directory if they match the URL
For example, if the client requests http://server/css/app.css then the file in src/css/app.css will be served
But if the client requests http://server/step-2 then since there is no file by that name the middleware will call next()
*/
app.use(express.static(__dirname + '/src'));
/* insert any app.get or app.post you need here. only if you do the advanced part */
/*
This says: for any path NOT served by the middleware above, send the file called index.html instead.
For example, if the client requests http://server/step-2 the server will send the file index.html. Then on the browser, React Router will load the appropriate component
*/
app.get('/*', function(request, response) {
response.sendFile(__dirname + '/src/index.html');
});
app.listen(process.env.PORT || 8080, function() {
console.log('server started');
});
Cannot find module 'express'
the reason is that you didn't install express yet.
solution: npm install express

Resources