Error: An unforeseen identifier was encountered while trying to import

I'm a newcomer to JavaScript and node.js. Whenever I attempt to launch the server using the "nodemon server.js" command, I encounter an unexpected identifier error. I have express installed.
Here is the content of my server.js file:

import express  from   'express' ; 
import mongoose from 'mongoose' ;


const app = express();
const port = proces.env.PORT || 8001 




app.get('/', (req, res) => res.status(200).send("hello ozzy") ); 


// Listener
app.listen(port, () => console.log(`listening on localhost: ${port}`)); 

And this is the information in my package.json file:

{
 "name": "bookvisor-backend",
 "version": "1.0.0",
 "description": "",
 "main": "server.js",
 "type": "module",
 "scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "nodemon server.js"
},
"author": "ozan",
"license": "ISC",
"dependencies": {
  "express": "^4.17.1",
  "mongoose": "^5.11.18"
},
"devDependencies":{
  "nodemon": "^2.0.7"
 }
}

This is the error message displayed:

import express  from   'express' ; 
   ^^^^^^^

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 Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
[nodemon] app crashed - waiting for file changes before starting...

Why am I getting this error?

Answer №1

It seems like you have already found the solution, but for others facing a similar issue, I encountered the exact same problem. Despite trying various solutions without success, I kept encountering an error with mongoose that mentioned TextEncoder not being found. However, after updating both NODE and NPM, all the errors disappeared.

NOTE

What issues did I experience?

  • ES6 syntax was not functioning even though I specified "type": "module" in the package.json
  • An error occurred when importing mongoose: new TextEncoder() is not defined

What attempts did I make to resolve the problem?

  • Removing and reinstalling all packages. Unsuccessful
  • Deleting node modules and reinstalling them. Unsuccessful
  • Completely deleting the project and rewriting it from scratch. Unsuccessful

What was the ultimate solution?

Simply updating the versions of npm and node. In my case, using Ubuntu,

For node:

  • sudo npm cache clean -f
  • sudo npm install -g n
  • sudo n stable

For npm:

  • sudo npm install -g npm

Answer №2

experiment with just Nodemon or Nodemon --exec npm start, or share the error message.

Answer №3

Make sure you have nodemon installed as a dev dependency for auto-reloading

An example of installation would be

npm install nodemon --save-dev

Once installed, update your package.json file to include the following in the scripts section

"Start": "nodemon my_file.js"

To start your application, simply run the command

npm start

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you retrieve the `categoryIds` key within an object that holds an array of mongodb's `ObjectId(s)` as its value?

In my Node.js code, I have the following: var getQuestionsByUserId = function (config) { var query = { _id: ObjectId(String(config.userId)) }; var projection = { categoryIds: true, _id: false }; var respondWithCategories = function (error, doc ...

Looking for a more efficient approach for my CircleCI testing process

My current CircleCI yaml file runs a separate test script for each app, which is not "DRY." I believe a better solution would be to run the test script from the root directory and loop over each app. However, I'm having trouble figuring out how to do ...

Experiencing TypeScript error in VSCode while trying to run in Nodejs? Here's how to troubleshoot and resolve

Experimenting with the performance measurement code provided by Nodejs in VSCode has been an interesting challenge for me. I encountered no issues running the code in Nodejs, and it executed smoothly. However, when attempting to run the code in VSCode, er ...

Using the app.use method in Node.js with Express

Currently, I am working on deciphering an old codebase: var express = require('express'); var app = express.createServer(); app .use('/run!', getUrl('app.sys', '/run')) .use('/stat', getUrl('app.sys& ...

Is it possible to use an external table in Node.js to query cloud storage?

Is it possible to query cloud storage using the external table concept in Node.js? I found some code in Python that achieves this functionality, but I would prefer to implement the same logic in Node.js. Is there a way to do this? ...

Leveraging Material-UI in Electron Environment

I'm currently working on an electron app using React and incorporating Material-UI for the user interface. I've added a datepicker and timepicker to a component, but when clicking on the input in the electron app, nothing happens. I'm unsure ...

Engaging storytelling within the boundaries of a Docker container

I have a unique docker container that is specifically designed to serve the node.js environment. It follows a similar configuration as explained in this informative article. However, I am interested in creating my own project. Is there any way to execute t ...

Is there variation in the node packages installed by various npm versions?

Node.js comes in two variations - LTS and the most current version. When utilizing npm install for package installation, is it true that the packages are installed regardless of which specific version of node.js is being used? Or do different versions of ...

Encountering an error while attempting to publish content on a different domain

Currently, I am attempting to send data in form-urlencoded format using Axios. Below is the code snippet: const qs = require("qs"); const axios = require("axios"); const tmp = { id: "96e8ef9f-7f87-4fb5-a1ab-fcc247647cce", filter_type: "2" }; axios .po ...

Alert: The flattening operation is not a recognized function. Proceed with --force option to proceed

I've encountered a strange error with Grunt. After some time in our CI system, the task grunt assemble:site starts to fail and outputs the following warning: Running "assemble:site" (assemble) task Warning: flatten is not a function Use --force to co ...

Tips for implementing and utilizing onclick functions in EJS

My goal is to develop a trivia game with interactive features. I aim to enable users to click on an answer, which will trigger a border effect and increase the points variable. Below is the layout of the entire page: <% include ../partials/boilerp ...

Issue with video not displaying in EJS template on node.js server

I have successfully uploaded a video using a node.js server and saved the FilePath to MongoDB in my /public/uploads folder. Within my ejs file, I am trying to display videos using the following code snippet: //Videos is an array of objects retrieved from ...

What is the best way to use PM2 for deploying my node.js application to various environments and ports within a single server?

I am facing an issue with deploying my node app using the ecosystem.json file and PM2. Despite trying various configurations, I have been unable to achieve my desired goal: To deploy the app in either a production or staging environment (both currently ...

Is Bcrypt password encryption for Golang also compatible with Node.js?

I have successfully implemented user authentication on my website using Node.js and Passport. However, I am now looking to migrate to Golang and need to figure out how to authenticate users using the passwords stored in the database. The encryption code ...

Express application receiving repetitive post requests

Recently, I have been working on developing a YouTube video conversion app that utilizes youtube-dl for streaming videos from YouTube and saving them. Everything was going smoothly until I encountered an issue when trying to stream a video that exceeded on ...

What is the best location to manage errors within a sequelize ORM query?

I am working with the Sequelize ORM within a Node/Express environment. My database has two tables: one for Users and another for Items. The Item table includes a foreign key that is linked to the UserId in the User table. Whenever I attempt to create an ...

What could be causing the continuous occurrence of the error message stating "Module 'socket.io' cannot be found"?

For the past few days, I've been attempting to incorporate socket.io into my NodeJS script. However, every time I run it, I encounter the frustrating error message stating "Cannot find module 'socket.io'". The detailed error is as follows: ...

Angular Boilerplate is experiencing difficulties in properly reading ABP

Working on my boilerplate project, I am now diving into consuming backend services (using asp .net) in Angular through http requests. However, I encountered an issue when trying to implement the delete method in mycomponent.ts, as TypeScript was not recogn ...

Error 584 occurred in the internal module/cjs/loader.js

Every time I try to run npm commands for my umi app project, an error pops up. Here is the specific error message that appears when I attempt to execute the code. I have made several attempts to locate the loader.js file within the node module, but unfort ...

What is the method for executing "npm install boombot" on a Heroku Server?

My goal is to quickly set up my project by running npm install boombot and editing the files using nano. After that, I plan to execute node index.js However, I encountered errors while trying to run heroku run npm install boombot --app trooperbot He ...