How to run ECMAScript (mjs files) with nodemon? - node.js

I am able to run mjs files with nodejs using --experimental-modules flag.
node --experimental-modules index.mjs
package.json:
{
"name": "mjs-tests",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.mjs"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"chalk": "^2.4.2",
"uuid": "^3.3.2"
},
"devDependencies": {
"nodemon": "^1.19.1"
}
}
And index.mjs
import http from 'http'
const server = http.createServer((req, res) => {
res.end('hello')
})
const PORT = 5000
server.listen(PORT, () => {
console.log(`🏃‍♀️ Server is running at http://localhost:${PORT}`)
})
But if I try to
npm run dev
or (with nodemon installed globally)
nodemon index.mjs
I get this error
[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.mjs`
internal/modules/cjs/loader.js:821
throw new ERR_REQUIRE_ESM(filename);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
So, How I can enable support for ECMAScript in nodemon? Or should I use something like esm?

Offcourse yes, All you need to modify your package.json a bit
"scripts": {
"dev": "nodemon --experimental-modules index.mjs"
},

Related

Server is not starting or connecting when using Nodemon

I just setup a new project using Express, Node and Nodemon. I setup the basics of the file to make sure it is starting but when I'm using npm start in the terminal it appears to start but it doesn't get a message of where the server has been started and when checking the localhost it is not connected. Not sure what the issue is.
below is my package.json
{
"name": "resturant-picker",
"version": "1.0.0",
"description": "Resturant picker app for Alchs",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/connordensmore/resturant-picker.git"
},
"keywords": [
"crud",
"mongodb"
],
"author": "Connor",
"license": "ISC",
"bugs": {
"url": "https://github.com/connordensmore/resturant-picker/issues"
},
"homepage": "https://github.com/connordensmore/resturant-picker#readme",
"dependencies": {
"axios": "^0.27.2",
"body-parser": "^1.20.0",
"dotenv": "^16.0.2",
"ejs": "^3.1.8",
"express": "^4.18.1",
"mongoose": "^6.5.5",
"morgan": "^1.10.0",
"node": "^18.8.0",
"nodemon": "^2.0.19"
}
}
below is my server.js
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
app.get("/", (req, res) => {
res.send("Crud App");
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
});
when i run npm start in the terminal this is the response and then nothing happens or is started from what i can tell.
mopdog#Connors-MacBook-Pro resturant-picker % npm start
> resturant-picker#1.0.0 start
> nodemon server.js
[nodemon] 2.0.19
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
[nodemon] clean exit - waiting for changes before restart
You never run listen because it's inside another function.
app.get("/", (req, res) => {
res.send("Crud App");
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

Unable to start node application inside docker

While creating my node app inside docker I am getting below error
docker container run -it --rm --volume $(pwd):/usr/src/app -p 7007:3000 sample-app-dev:latest
docker: Error response from daemon: OCI runtime create failed: container_linux.go:344: starting container process caused "exec: \"nodemon server.js\": executable f
My Dockerfile looks like below
FROM node:12
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
ENV PATH="/usr/src/app:${PATH}"
ENTRYPOINT ["nodemon server.js"]
Package.json
{
"name": "nodedocker",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"nodemon": "^2.0.4"
}
}
server.js
const express = require( "express" );
const app = express();
const port = 3000;
app.get( "/", ( req, res ) => {
res.send( "Hello World from express JS!!" );
} );
const hobbies = [
"Swimming", "Diving", "Jogging", "Cooking", "Singing" ] ;
app.get("/hobbies", (req, res) => {
res.send(hobbies);
});
const famous_programming = [
"python", "java", "c", "c++", "JS" ] ;
app.get("/famous_programming", (req, res) => {
message = famous_programming.includes("node")? "Yaaay, Node.js" : "Yup! Node.js is a framework from JS" ;
res.send(message);
});
app.listen( port, () => {
console.log( `Node JS started on http://localhost:${port}` )
} );
I am not sure what else I am missing here, any inputs greatly appreciated.
Thank you.
You could configure the package to run nodemon server.js on start, then specify npm start in the entrypoint:
Dockerfile:
FROM node:12
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
ENV PATH="/usr/src/app:${PATH}"
ENTRYPOINT ["npm", "start"]
package.json:
{
"name": "nodedocker",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"nodemon": "^2.0.4"
}
}
Test:
$ docker container run -it --rm q63534772
> nodedocker#1.0.0 start /usr/src/app
> nodemon server.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Node JS started on http://localhost:3000

NodeJS website uploaded to Heroku won't load, can't find dependencies for some reason

Tried to upload my website to an Heroku server.
It's not my first time and I usefully do not encounter any problems. I have added a profcile.
This is the package.json:
{
"name": "exodia-coming-soon",
"version": "1.0.0",
"description": "Coming Soon\r http://exodia.io",
"main": "server.js",
"dependencies": {
"express": "^4.16.3",
"nodemon": "^1.18.4",
"path": "^0.12.7"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Amirh24/exodia-landing.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/Amirh24/exodia-landing/issues"
},
"homepage": "https://github.com/Amirh24/exodia-landing#readme"
}
What matters is the dependencies and
devDependencies part.
When I upload it to heroku and it wont load, the logs show:
2018-09-26T12:09:21.012703+00:00 app[web.1]: > exodia-coming-soon#1.0.0 start /app
2018-09-26T12:09:21.012705+00:00 app[web.1]: > nodemon server.js
2018-09-26T12:09:21.012706+00:00 app[web.1]:
2018-09-26T12:09:21.107321+00:00 app[web.1]: module.js:550
2018-09-26T12:09:21.107325+00:00 app[web.1]: throw err;
2018-09-26T12:09:21.107326+00:00 app[web.1]: ^
2018-09-26T12:09:21.107329+00:00 app[web.1]: Error: Cannot find module '../lib/cli'
When I try to start without nodemon, just node server.js I get:
2018-09-26T11:49:07.146721+00:00 app[web.1]: > node server.js
2018-09-26T11:49:07.146723+00:00 app[web.1]:
2018-09-26T11:49:07.257964+00:00 app[web.1]: module.js:550
2018-09-26T11:49:07.257968+00:00 app[web.1]: throw err;
2018-09-26T11:49:07.257969+00:00 app[web.1]: ^
2018-09-26T11:49:07.257971+00:00 app[web.1]:
2018-09-26T11:49:07.257973+00:00 app[web.1]: Error: Cannot find module './lib/express'
I have installed my 3 dependencies: express, path and nodemon a couple of times with both --save and -g variants. What am I doing wrong?
Where is that error being thrown? It looks like you're trying to use files in a relative position, not express in node_modules. Does your project have a lib folder? Are you uploading it as well?
You can uninstall the global express with npm uninstall -g express. Delete your node_modules folder and start fresh with npm install and npm start. Does it run locally?

Babel 7 with Express

I am trying to use Babel 7 with Express and I have resolved all errors that have come my way, but I cannot get the Express server to start. I'm unsure if this is because there is no substitute (to my knowledge) for babel-node or if I am doing something wrong.
Here is my package.json
{
"name": "MEAN-Package",
"version": "0.1.0",
"description": "A package for the exercises",
"main": "index.js",
"author": "Chasen Bettinger",
"license": "MIT",
"scripts": {
"start": "nodemon server.js --exec babel"
},
"dependencies": {
"connect": "^3.6.6",
"express": "^4.16.3",
"mongodb": "^3.0.4"
},
"devDependencies": {
"#babel/cli": "^7.0.0-beta.42",
"#babel/core": "^7.0.0-beta.42",
"#babel/preset-env": "^7.0.0-beta.42",
"nodemon": "^1.17.2"
}
}
Here is server.js
import express from "express";
const app = express();
app.use("/", (req, res) => {
res.status(200).send("Hello World");
});
app.listen(3000);
console.log("Server running at http://localhost:3000/");
export { app as default };
My .babelrc file
{
"presets": ["#babel/preset-env"]
}
Console output:
Trying to learn express so any help is appreciated!
You should you babel-node instead of babel. Follow these steps to fix it:
Add babel-node:
yarn add #babel/node --dev
2- Change your start script on package.json to:
"scripts": {
"start": "nodemon server.js --exec babel-node",
}
You should not be using babel-node in production. It is unnecessarily heavy, with high memory usage due to the cache being stored in memory. You will also always experience a startup performance penalty as the entire app needs to be compiled on the fly.
the correct way is:
npm i -D #babel/node
and
"scripts": {
"start": "nodemon server.js --exec babel-node",
}
npm run start

How to add multiple NODE_PATH in package.json?

How do I add multiple NODE_PATH in package.json?
I want to have these multiple paths:
NODE_PATH=./ NODE_PATH=./modules/
or
NODE_PATH=./lib NODE_PATH=./modules/
package.json:
{
"name": "my-app",
"description": "env",
"repository": "https://github.com/xxx.git",
"scripts": {
"dev": "NODE_PATH=./lib NODE_PATH=./ node server.js",
"start": "cross-env NODE_ENV=production NODE_PATH=./ NODE_PATH=./modules/ nodemon --exec babel-node --presets es2015 server.js"
},
"dependencies": {
"cross-env": "^5.0.5",
"express": "^4.15.4"
},
"license": "MIT"
}
server.js:
'use strict'
import express from 'express'
import sample from 'lib/sample'
import config from 'lib'
const app = express()
const isProd = (process.env.NODE_ENV === 'production')
const port = process.env.PORT || 3000
console.log(isProd)
console.log(sample)
console.log(config)
app.get('/', function (req, res) {
const data = {message: 'Hello World!'}
console.log(data);
return res.status(200).json(data);
})
app.listen(port, function () {
console.log('listening on port 3000!')
})
Error:
Error: Cannot find module 'lib/sample'
Any ideas?
The way you are using NODE_PATH in your example, by setting it twice, you are overwriting the writing the value you assign first with the second time.
Instead, set NODE_PATH to multiple paths, delimited by colons (on MacOS or Linux) or semicolons (Windows), like this:
{
"name": "my-app",
"description": "env",
"repository": "https://github.com/xxx.git",
"scripts": {
"dev": "NODE_PATH=./lib:./ node server.js",
"start": "cross-env NODE_ENV=production NODE_PATH=./:./modules/ nodemon --exec babel-node --presets es2015 server.js"
},
"dependencies": {
"cross-env": "^5.0.5",
"express": "^4.15.4"
},
"license": "MIT"
}
See Node.js documentation:
https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

Resources