ReferenceError: TextEncoder is not defined Node.js with mongoose - node.js

the problem seems to be with mongoose & mongodb packages as it works fine when
mongoose.connect('mongodb+srv://mydb:<password>#cluster0.w1opr.mongodb.net/test?retryWrites=true&w=majority');
is removed
it also works fine on repl.it cloud env
here is my code
var express = require('express');
var ejs = require('ejs');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb+srv://mydb:<password>#cluster0.w1opr.mongodb.net/test?
retryWrites=true&w=majority');
app.set('view engine','ejs')
app.use(bodyParser.urlencoded({extended: true}));
.
.
.
app.listen(3000,function(){
console.log('Server is running on port 3000');
});

Actually mongoose 6 requires Node 12 or higher, so this is expected behavior. Mongoose 6 does not support Node 10.So updating Node version will fix the issue. It also fix the problem by downgrading mongoose version to 5.

Check your node version, if it's lower than 12 it won't work, if that's the case updating node should do do the job. You could downgrade your mongoose version too.
There's an issue closed on Mongoose github page.
https://github.com/Automattic/mongoose/issues/10638

To get rid of this error in Windows upgrade to the latest version of Node.js by visiting this site https://nodejs.org/en/download/ and downloading the latest version of Node.js else if you do not want to upgrade to the latest version then you can get rid of this error by adding this line at the top of the file in node_modules/whatwg-url/dist/encoding.js:
const {TextDecoder, TextEncoder} = require("util");

Had the same problem when using tests. Setting the testEnvironment to node in my jest config fixed it (https://mongoosejs.com/docs/jest.html)
module.exports = {
testEnvironment: 'node'
};

For me i'm using UBUNUTU 20.04, as #MuhammadTariq said my node version was 10 and after upgrading the version to 16 the error is gone.

Related

How to deploy the node.js application on server with different node version

I want to deploy my node app on server. but when I upload the node app to our server and then add node.js instalation then It is not opening the file. the index.js file is
const connectToDb = require("./DBconfig");
const express = require('express')
const router = express.Router();
var cors = require('cors');
connectToDb();
const app = express();
const port = process.env.PORT | 5000;
app.use(cors());
app.use(express.json());
connectToDb();
app.use( '/api/user' ,require('./routes/user') );
app.use( '/api/post' ,require('./routes/post') );
app.get('/', (req, res) => {
res.send('The site is start now')
})
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
const path = require("path");
app.get("*",(req,res)=>{
res.sendFile(path.resolve(__dirname,'client','build','index.html'))
})
}
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
The node version in my local machine is v16.14.0 but the node version that the NameCheap is given is v14.18.3
the node installation in Namecheap that I configure is the installation of node
the error message is triggered, when I hit the URL of API API's URL, is the error message. I am unable to find the solution to solve this problem. I read some articles in which the writer tells that this type of error occurs when we use the different node versions in the local machine and on the server machine but I can't do anything because I restrict to use of the v14.18.3 on the server-side but I used the v16.14.0 in my local machine. can anyone tell me the solution to solve this type of problem?
webi is also a great tool. I recommend completely uninstalling node and installing it fresh with webi.
# this will install node and the webi cli
# Linux/Mac
curl -sS https://webinstall.dev/node | bash
# Windows
curl.exe -A "MS" https://webinstall.dev/node | powershell
# then you can run the following to switch versions
webi node#14
See https://webinstall.dev/node/ for more info.
nvm is another useful tool that can help you to control the node version itself, you can use nvm commands to upgrade the node version quite easily.
nvm install <version-number>
nvm use 0.10
using nvm use -nodeversion you can switch your node js version to your server node js version.

node app.js localhost not working

on WINDOWS ...after install express-seed and node.js for the "blog" tutorial, i get the same cmd prompt after typing node app.js.
another time i got body parser and error handling errors
i tried alot of solutions, even had a local host run with another tutorial, but i would like to run from the blog tutorial due to some slight differences of the set-up.
Of course im a newb, and i know theres tons of answers on the forum, but none are correcting my issue...please help.
and everytime i try to post my report on here it errors me saying i have to indent each line 4 spaces. im just losing in general.
Is there a step im missing? all the tut's say just do 'this' and 'this' and i have a local host running so i can make changes to views. any help?
// Module dependencies.
var express = require('express');
var app = express.createServer();
// Configuration
app.configure( function() {
});
// Routes
app.get('/', function(req, res) {
res.send('Hello World');
});
app.listen(3000);
what version of node & express are you running?
From the command line you can check with:
node --version
and
express --version
From your code, it looks like an older version of express (version 3 or less), but I'm betting you didn't specify the version on the npm install, which will give you the latest version (4+). There's a lot of breaking changes between those versions, so you can't run old code with the new framework successfully. My bet is that your blog tutorial hasn't been updated to express 4.x yet.

Error with Simple Express Server and Gulp

I'm trying to run a simple Express web server using a gulp task. I only want a static server that displays the index file. I can easily perform this by running a node module, but again, I want to do this in gulp. I plan on expanding this to allow a LiveReload server to be set up.
I have followed many tutorials on setting up LiveReload but they are failing. I'm assuming it has something to do with the versions being used with respect to when the articles are written. But I was hoping maybe somebody had an idea on how to handle this.
I have created a very small Github repo that allows you to play around with what I'm trying to accomplish: fixit
Gulpfile.js:
var gulp = require('gulp');
var EXPRESS_PORT = 4000;
var EXPRESS_ROOT = __dirname;
gulp.task('express', function () {
var express = require('express');
var app = express();
app.use(express.static(EXPRESS_ROOT));
app.listen(EXPRESS_PORT);
});
*There is an index.html in the same directory as the Gulpfile
And here is the error:
/var/www/clients/client1/web14/sendus-admin/node_modules/express/node_modules/etag/index.js:55
throw new TypeError('argument entity must be string or Buffer')
^
TypeError: argument entity must be string or Buffer
at etag (/var/www/clients/client1/web14/sendus-admin/node_modules/express/node_modules/etag/index.js:55:11)
at SendStream.setHeader (/var/www/clients/client1/web14/sendus-admin/node_modules/express/node_modules/send/index.js:724:15)
at SendStream.send (/var/www/clients/client1/web14/sendus-admin/node_modules/express/node_modules/send/index.js:500:8)
at onstat (/var/www/clients/client1/web14/sendus-admin/node_modules/express/node_modules/send/index.js:585:10)
at Object.oncomplete (fs.js:97:15)
I had the same problem and after a week without Gulp and BrowserSync working (the combination giving me the same error), I resorted to more severe options like reinstalling Node.js. In the end, what worked for me was to use nvm to downgrade to Node.js version 10 (I was using 11 before).
nvm install 0.10
nvm use 0.10
Then just updated and used Gulp:
npm update
gulp
Sure hope that helps you too.
I had the same problem with Express.static since a week. Disabling ETAG for Express.static solves this problem for me untill there is a better fix:
app.use(express.static(path.join(__dirname, '/static'), {etag: false}));

How to set up an Express 4.0 application

I downloaded express today from npm, and to my surprise, it gave me express 4.0.0 instead of express 3.x.x.
I'm trying to configure a basic server with connect logger and body parser, but I'm not having much luck.
Could someone provide me with a boilerplate app.js file using express 4.0?
Thanks!
Got it!
You can get a skeleton app using:
$ npm install -g express-generator
Alternatively, you can swap out the connect logger and body parser for their connect standalone siblings (and it might be useful for learning what each middleware does, rather than relying on the generator to throw together a bunch of dependencies you may not need):
(based on Express 3.x to 4.x Migration guide)
var express = require('express');
var server = express();
...
server.use(require('body-parser')); //previously bodyparser (or rather urlencoded/json)
server.use(require('morgan')()); //previously connect-logger
...
server.listen('3000', function() {
console.log('server started');
});

node.js + express 3 + socket.io = Can't set headers after they are sent

I'm new to learning node.js and seem to have run into an error that can't get to fix.
Its a very simple and beginners code so shouldn't need much explanation, more over it works fine on localhost, but breaks on production server.
App.js
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 8000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
var server = app.listen(8000);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
And here's the dreaded error!
http.js:644
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:644:11)
at ServerResponse.res.setHeader (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/patch.js:59:22)
at next (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/proto.js:153:13)
at Function.app.handle (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/proto.js:198:3)
at Server.app (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/connect.js:66:31)
at Manager.handleRequest (/home1/artalatc/public_html/cloud1/node_modules/socket.io/lib/manager.js:564:28)
at Server.<anonymous> (/home1/artalatc/public_html/cloud1/node_modules/socket.io/lib/manager.js:118:10)
at Server.EventEmitter.emit (events.js:115:20)
at HTTPParser.parser.onIncoming (http.js:1793:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
Problem seems to be at var io = require('socket.io').listen(server); because commenting this like removes the error.
What version of Node are you using?
I had the same problem when I was using 0.9.x. I downgraded Node to 0.8.4 and the problem seems to have gone away.
My best guess is something in Node has changed that Socket.io doesnt agree with.
upgrade
express - 3.1.0 and socket.io - 0.9.13
it's ok on nodejs0.10
Which version of express are you using? Check out https://github.com/visionmedia/express/wiki/Migrating-from-2.x-to-3.x or try this:
var server = app.listen(8000);
var io = require('socket.io').listen(server);
i was having the same issue mate
if you are using express 3.0 you should try this:
http://codehenge.net/blog/2012/08/using-socket-io-with-express-3-x/
also check your version of node:
node --version
try using v0.8.9 or any other stable version
It helped me! And will help you
For anyone bumping in to this issue you should be using:
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
As express no longer returns a HTTP instance that socket.io requires. See the updated README.md file on https://github.com/learnboost/socket.io for the express 2 and 3 examples.
This approach works in the current stable release 0.8.14:
var express = require('express')
, app = express()
, server = app.listen(8000)
, io = require('socket.io').listen(server);
I had the exact same issue. Incompatible versions of express and socket.io were to blame. Upgraded them to express 3.2.4 and socket.io 0.9.14 and works like a charm.
Or you can downgrade your socket.io to a previous version, but you'll have to figure that one out.
this error come because express internally use cache means for every second request data get from cache so it response back with 304 status code so use
app.disable('etag');
it tells the express each request fresh means with stautscode 200
Change socket.io dependency to 0.9.15 in package.json, run npm install and it should fix your problem.
Run a npm list socket.io
Make sure it doesn't show invalid as below,
─ socket.io#0.9.10 invalid
npm ERR! invalid: socket.io#0.9.10 c:\Users....
If you get this error, npm install socket.io.
Also make sure the same with other packages.

Resources