0

this is my server.js file to import http from http module. i need to make my server.js file a module and import it in the index.js file which is the entry to my app.

   import { createServer } from 'http'; 
   function start(){
       function onRequest(req,res){
           console.log("Request recieved");
           res.writeHead(200, {"content-type":"text/plain"});
           res.write("Good afternoon Paullaster");
           res.end();
       }

       createServer(onRequest).listen(8080);
       console.log("Response ready");
   }

   export { start};

this is my index.js file that should be the entry point to my application

import server from "./server";
server.start()
                                                                                       

i get this error

PS C:\Users\paullaster-geek\OneDrive\Desktop\Projects\Dive node> node -r esm index.js
C:\Users\paullaster-geek\OneDrive\Desktop\Projects\Dive node\index.js:1
SyntaxError: The requested module 'file:///C:/Users/paullaster- 
geek/OneDrive/Desktop/Projects/Dive%20node/server.js' does not provide an export named 'default'
at internal/main/run_main_module.js:17:47
PS C:\Users\paullaster-geek\OneDrive\Desktop\Projects\Dive node>

i have added an esm to my project

//npm init esm

and

 npm i esm
James Z
  • 12,209
  • 10
  • 24
  • 44

2 Answers2

1

Try:

import { start } from "./server";
start()

or see more about here module.exports vs. export default in Node.js and ES6

0

If you want to write server.start(), I would recommend

import * as server from "./server";

but @StanimirGeorgiev's suggestion is fine as well.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375