Docker & Nodejs - ReferenceError: TextEncoder is not defined - node.js

I'm encountering the following error while trying to launch my docker container:
Error:
server_1 | /usr/src/app/node_modules/whatwg-url/lib/encoding.js:2
server_1 | const utf8Encoder = new TextEncoder();
server_1 | ^
server_1 |
server_1 | ReferenceError: TextEncoder is not defined
Dockerfile:
FROM --platform=linux/amd64 node:current-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "run", "prod"]
docker-compose.yml:
version: '3'
services:
server:
build:
context: ./server
ports:
- "3008:3002"
environment:
API_PORT: "3002"
DB_HOST: "192.168.1.211"
DB_PORT: "27018"
DB_NAME: "tutorialitems"
restart: always
index.js file:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser({ limit: '50mb' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//DB
const db = require('./models');
const dbConfig = require('./config/db.config');
try {
db.mongoose.connect(`mongodb://${dbConfig.HOST}:${dbConfig.PORT}/${dbConfig.DB}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
console.log('DB Connected!');
} catch (error) {
console.log('Cannot connect to DB...', error);
process.exit();
}
//Routes
require('./routes/crud.routes')(app);
app.get('/', (req, res) => {
res.json("Server is Running")
});
app.listen(process.env.API_PORT, () => {
console.log(`Server is listening on port ${process.env.API_PORT}`)
});
What I tried (but unsuccessfully):
I updated the following file: node_modules > whatwg-url > lib > encoding.js from
Initial:
"use strict";
const utf8Encoder = new TextEncoder();
const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
to Updated:
const util = require("util");
const utf8Decoder = new util.TextEncoder("utf-8", { ignoreBOM: true });
package.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",
"prod": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"mongoose": "^6.1.5",
"nodemon": "^2.0.15"
}
}
But when I run my docker-compose, I still have the same error.
Anyone has an idea?
Thks

Mongoose v6.1.5 is working with Node 17.3.0.
Package.json
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",
"prod": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"mongoose": "^6.1.5",
"nodemon": "^2.0.15"
}
}
After updating my package.json with the Mongoose 6.1.5 version, and my Dockerfile as following:
FROM --platform=linux/amd64 node:17.3.0
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "run", "prod"]
I run the following docker-compose commands:
docker-compose pull
docker-compose build
docker-compose up
And now it's working. It seems that docker-compose up was still using the previously build version... thus, it was not working...

package.json:
"mongoose": "^6.2.7"
DockerFile:
FROM node:17-slim
I was getting the same error, when I set the versions as above (node:16-slim to 17-slim), my problem went away. Thanks..

Related

Dockerized Node API using official Node image

The below code runs the server.js without installing the node modules in the package.json, so it run into an error Error: Cannot find module 'koa'. Is it possible to install node modules on the prebuilt Docker Node image (https://github.com/nodejs/docker-node) using docker-compose?
I tried command: "yarn install && yarn start" in docker-compose.yml, but that's not valid.
docker-compose.yml
version: "3.8"
services:
my-api:
image: node:16-alpine
user: node
working_dir: /home/node/app
volumes:
- ./:/home/node/app
- /home/node/app/node_modules
command: "yarn start"
expose:
- 5000
ports:
- 5000:5000
package.json
{
"name": "my-api",
"private": true,
"scripts": {
"install": "yarn install",
"start": "node server.js"
},
"main": "server.js",
"dependencies": {
"koa": "^2.13.0",
"#koa/cors": "^3.1.0",
"koa-bodyparser": "^4.3.0",
"koa-logger": "^3.2.1",
"koa-router": "^9.0.0"
}
}
server.js
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const logger = require('koa-logger');
const Router = require('koa-router');
const cors = require('#koa/cors');
console.log('server ready');

Nodemon throwing error: address already in use <port number> on M1 Mac

I'm trying to use nodemon on my macbook and whenever i run
nodemon <script.js>
It gives me this error:
address already in use <PORT NUMBER HERE>
Even if i'm running the script for the very first time. I've tried
npx kill-port <port>
But it doesn't work: it shows that a process was killed but when i try to run nodemon again, i get the same error.
Here's my package.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^10.0.0",
"express": "^4.17.1",
"nodemon": "^2.0.7"
}
}
My server.js:
const express = require("express");
const dotenv = require("dotenv");
const app = express();
dotenv.config();
const PORT = process.env.PORT;
app.get("/getRestaurants", (req, res) => {
console.log("Get All Restaurants");
});
app.listen(PORT, () => {
console.log(`Server is up on port ${PORT}`);
});
And my .env:
PORT = 4000;
What could be causing this? I'm on a M1 MBA with bigsur.

Deploying to GCP App Engine with React Frontend and Node backend not able to hit api routes on deployed version by works locally

I have deployed my site to google cloud platform and the react(static) part is working fine, but anytime I go to /api/mail/send to use nodemailer I either get a 404 error saying it cant be found or with some configurations in the yaml file I just a 500 error.. below is my yaml, package.json and server.js files
App.yaml
runtime: nodejs12
env: standard
basic_scaling:
max_instances: 5
idle_timeout: 5m
handlers:
- url: /api/.*
secure: always
script: auto
- url: /
static_files: client/build/index.html
upload: client/build/index.html
secure: always
- url: /
static_dir: client/build
secure: always
Package.json
{
"name": "mern",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "concurrently \"nodemon --ignore 'client/*'\" \"npm run client\"",
"client": "cd client && npm run start",
"install": "cd client && npm install",
"build": "cd client && npm run build"
},
"author": "",
"license": "ISC",
"devDependencies": {
"autoprefixer": "^9.8.6",
"concurrently": "^5.3.0",
"husky": "^4.2.5",
"postcss-cli": "^7.1.1",
"tailwindcss": "^1.6.2"
},
"dependencies": {
"if-env": "^1.0.4",
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"classnames": "^2.2.6",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-session": "^1.17.1",
"morgan": "^1.10.0",
"nodemailer": "^6.4.11"
}
}
server.js
require('dotenv').config()
const express = require("express");
const morgan = require('morgan');
const routes = require("./routes");
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3001;
// Define middleware here
app.use(morgan('dev'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Add routes, both API and view
app.use(routes);
// Serve up static assets (usually on heroku)
app.use(express.static("client/build"));
// Start the API server
app.listen(PORT, function() {
console.log(`🌎 ==> API Server now listening on PORT ${PORT}!`);
});
Thanks

unable to use .env variables in express js

I am new to node and express js facing issue to access .env variables
webapp.js:
const express = require("express");
const app = express();
require('dotenv').config();
app.listen(process.env.app_port, () => {
//console.log("server running....", process.env);
console.log("server running....", process.env.app_port);
});
.env file:
node_env : development
app_port : 5000
db_port : 3306
host : localhost
user : root
password :
database : job_portal
connectionLimit : 10
package.json
{
"name": "webservices",
"version": "1.0.0",
"main": "webapp.js",
"scripts": {
"start": "nodemon webapp.js",
"dev": "nodemon webapp.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.0",
"express": "^4.17.1",
"mysql": "^2.18.1"
},
"devDependencies": {
"cross-env": "^7.0.2",
"dotenv": "^8.2.0",
"nodemon": "^2.0.4"
},
"description": ""
}
I am trying to access variable in webapp.js from .env file but it return undefined how to fix this?
change your.env file to
node_env = development
app_port = 5000
db_port = 3306
host = localhost
user = root
#YOU VARIABLES SHOULD CAPITALISE AS THIS IS THE CONVENTION
NODE_ENV=development
APP_PORT=5000
DB_PORT=3306
HOST=localhost
USER=root

Implement Nodejs with pm2 start in Docker

I have a nodejs app. The app runs with pm2. When I execute "pm2 start app.js". pm2 is started. But when I do curl http://localhost:3000 , it says : Failed to connect to localhost port 3000: Connection refused. But port 3000 is open. I am confused, Please help me out.
My Dockerfile
FROM keymetrics/pm2:latest-alpine
# Create app directory
RUN mkdir -p /usr/cl/app
WORKDIR /usr/cl/app
# Install app dependencies
COPY package*.json ./
COPY . .
RUN npm install
RUN npm install pm2 -g
EXPOSE 3000
CMD [ "npm", "start" ]
My Package.json
{
"name": "cs",
"version": "1.0.0",
"description": "Cs",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "pm2 start app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"async": "^2.6.0",
"axios": "^0.18.0",
"base64-encode-decode": "0.0.3",
"body-parser": "^1.18.3",
"cors": "^2.8.4",
"csv": "^1.2.1",
"csv2sql-lite": "0.0.6",
"dotenv": "^4.0.0",
"epipebomb": "^1.0.0",
"express": "^4.16.3",
"fast-csv": "^2.4.1",
"getmac": "^1.4.1",
"ini": "^1.3.5",
"js-md5": "^0.7.3",
"multer": "^1.3.0",
"node-cache": "^4.2.0",
"node-xlsx": "^0.12.0",
"nodemailer": "^4.6.4",
"os": "^0.1.1",
"pg": "^6.4.2",
"serve-static": "^1.13.2",
"trim": "0.0.1"
}
}
Docker image and container is created. But when I do curl http://localhost:3000
Error says "Failed to connect to localhost port 3000: Connection refused. But port 3000 is open. I am confused, Please help me out.
app.js file is
"var express = require('express');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
require('dotenv').config({path: 'inireader.env'});
var app = express();
const port = 3000;
const routepostgres = require('./routes/routepostgres');
app.use(cors());
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.use(express.static(path.join(__dirname,'public')))
app.use('/api', routepostgres);
app.listen(port, function(req, res){
console.log('Server started at port:'+ port);
});
app.get('/', function(req, res){
res.send('Welcome # browser');
console.log('Welcome # Console');
});

Resources