javascriptnode.jsexpress

Can't run "node index.js" due to a syntaxError


My code is the following;


import express from "express";

const app = express();
const port = 3000;

app.listen(port, () =>{
    console.log(`Server is running on ${port}.`)
});

I don't understand what the issue is here. I'm following a course and followed the suggested steps yet I don't really know how to fix this.

node index.js
     ^^^^^
Uncaught SyntaxError: Unexpected identifier 'index'

I thought it was a syntax error in the code but I can't find anything. Error makes it sounds like it doesn't like the name 'index' which I thought was funny.

I ran npm install express, then node, node index.js. Nothing super complex, is it possible the course is outdated and some syntax here is no longer valid? (Relatively new to coding, mainly in javascript!)


Solution

  • The error message suggests you entered node index.js from inside node.

    PS C:\git\foo> node
    Welcome to Node.js v20.11.0.
    Type ".help" for more information.
    > node index.js
    node index.js
         ^^^^^
    
    Uncaught SyntaxError: Unexpected identifier 'index'
    >
    

    You should first exit node, then from the regular command prompt (bash, PowerShell, cmd.exe), enter node index.js.

    node without arguments brings you in the REPL, which is an interactive JavaScript interpreter. It only understands JavaScript plus a handful of special commands. "node index.js" is not a valid JavaScript command, hence the error. What you can do is load and run index.js with the .load command.

    PS C:\temp> cat index.js
    console.log('Hello world');
    PS C:\temp> node
    Welcome to Node.js v20.11.0.
    Type ".help" for more information.
    > .help
    .break    Sometimes you get stuck, this gets you out
    .clear    Alias for .break
    .editor   Enter editor mode
    .exit     Exit the REPL
    .help     Print this help message
    .load     Load JS from a file into the REPL session
    .save     Save all evaluated commands in this REPL session to a file
    
    Press Ctrl+C to abort current expression, Ctrl+D to exit the REPL
    > .load index.js
    console.log('Hello world');
    
    Hello world
    undefined
    > .exit
    PS C:\temp>
    

    See also: https://nodejs.org/en/learn/command-line/how-to-use-the-nodejs-repl