Unable to transpile ES6 express server using Parceljs in development mode - javascript

I am trying to transpile an ES6 express app using Parceljs.
Trying to run the parcel dev server using yarn parcel index.js displays that it is running at localhost:1234 but the page is blank. It also generates the following output when trying to run node dist/index.js:
index.js:116
throw error;
^
TypeError: Cannot read properties of undefined (reading 'prototype')
Running yarn parcel index.js --target node does not yield any localhost port for me to test the API with. However, the API now works as I can use node dist/index.js to run the script but now I have to resort to npx nodemon /dist/index.js to have file watching.
Here is the sample code.
index.js
import express from "express";
const app = express();
const port = 5000;
app.get("/", (req, res) => {
res.json({ msg: "Hello!" });
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
package.json
...
"dependencies": {
"express": "^4.17.3",
"parcel": "^2.3.2",
"parcel-bundler": "^1.12.5"
}
...
I would greatly appreciate a solution that allows me to use Parceljs to watch for file updates directly, preferably with HMR.

See issue 355: Is parcel meant to work with server-side code insluding HMR?: parcel does not (yet) support hot module reloading in nodejs.

parcel creates a web server and serve your code but express need to be called by itself to be able create a web server and server requests.
You'd better use babel & nodemon instead of parcel
I use command bellow
nodemon --exec babel-node src/index.js

Related

filesending for index.html overrides all get apis

I have MERN application, where I serve index.html on all routes. But bellow that, I declare another apis for request.
router.post('/add-bin', newBin);
router.get('/recent-bins', recentBins);
router.get('/fetch-bin/:filename', fetchBin);
app.use(router);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html')); // Front is built with react
});
In the development mode, where I was using proxy, everything was going fine, but when I deployed my web application on heroku, All the GET apis are overrode by that app.get("*" ...) part.
P.S I am quite new to Node and Express.
First, in client run npm run build this will generate the build folder, where will be your frontend production code. In your backend you should serve that folder (this usually will be done in your index.js).
app.use(express.static('path/to/client/build'))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html')); // Front is built with react
});
After that, you'll need to add some commands (in your package.json) to prepare the client for the deploy.
"scripts": {
"build": "cd path/to/client && npm run build",
//we'll need to install client packages
"i-client-packages": "cd client && npm install",
//heroku will execute this command post-build
//this will be needed to run the previous commands
"heroku-postbuild": "npm run i-client-packages && npm run build"
//...the other commands (start, test, etc...)
}
More info about how to deploy a MERN app to heroku here.

How to run node js application without terminal command

I'm so new in node.js and I have a simple node.js project with only one js file (vpn.js) which use a module and an index.html which opens using a function in vpn.js. I have installed this package and the require function can find its module. I have a vpn.js file and an index.html (in index.html I only have a video tag with a src.). Now my question is should I always run my code with terminal? how should I host this project? Basically no clients can run terminal commands on web. (note: I'm using Windows not Linux)
this is the code of my js file:
const openvpnmanager = require('node-openvpn');
const opts = {
host: '192.168.1.7', // normally '127.0.0.1', will default to if undefined
port: 8080, //port openvpn management console
timeout: 1500, //timeout for connection - optional, will default to 1500ms if undefined
logpath: 'log.txt' //optional write openvpn console output to file, can be relative path or absolute
};
const auth = {
user: 'vpnUserName',
pass: 'vpnPassword',
};
const openvpn = openvpnmanager.connect(opts)
// will be emited on successful interfacing with openvpn instance
openvpn.on('connected', () => {
//openvpnmanager.authorize(auth);
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('index.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(5500);
});
// emits console output of openvpn instance as a string
openvpn.on('console-output', output => {
console.log(output);
});
// emits console output of openvpn state as a array
openvpn.on('state-change', state => {
console.log(state)
});
// emits console output of openvpn state as a string
openvpn.on('error', error => {
console.log(error)
});
Use pkg npm package. This will create an executable file for your nodejs project. You can create executable file for Windows or mac or linux.
Install pkg globally using following command
npm install -g pkg
After installing it, use:
pkg app.js[entry file to your project] to create executable file.
For more info about pkg, look into pkg
you can done it help of set autorun the node server forever.
here is some step
You may also want to consider using the upstart utility. It will allow you to start, stop and restart you node application like a service. Upstart can configured to automatically restart your application if it crashes.
Install upstart:
sudo apt-get install upstart
Create a simple script for your application that will look something like:
#!upstart
description "my app"
start on started mountall
stop on shutdown
# Automatically Respawn:
respawn
respawn limit 99 5
env NODE_ENV=production
exec node /somepath/myapp/app.js >> /var/log/myapp.log 2>&1
Then copy the script file (myapp.conf) to /etc/init and make sure its marked as executable. Your application can then be managed using the following commands:
sudo start myapp
sudo stop myapp
sudo restart myapp

Why am I getting a syntax error or server not defined error when running node server.js in command line for windows?

I have tried opening my server.js file multiple times as well as a test file i named helloworld.js in cmd as well as gitbash and gitcmd. Everytime I am returned with some sort of error whether it is a syntax:
or a cannot find module socket.io error
I have tried many things and ways including downloading gitbash and trying it there. I am fully new to any coding or dev and have read all of the other 20+ psots regarding the same thing but none of them seemed to have been resolved or documented?
Thank you
In your first attempt:
node server.js is a command you are expected to run on your shell (bash, Windows Power Shell, etc). It launches Node.js and tells it to run the server.js module.
You are running node at the shell, which launches node and presents you with a REPL. You are then trying to run node server.js as if it were JavaScript (which it isn't, because it is shell).
Where you are currently typing node, instead type node server.js.
In your second attempt:
You are trying to load a module called socket.io, but it is not installed. You have to install it first.
Look at the getting started guide for Socket.io.
It tells you how to set up a package manifest:
First let’s create a package.json manifest file that describes our
project. I recommend you place it in a dedicated empty directory (I’ll
call mine chat-example).
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {}
}
and install modules while recording them as dependancies for your package:
During development, socket.io serves the client automatically for us,
as we’ll see, so for now we only have to install one module:
npm install --save socket.io
If you have not already, go through the Getting Started guide on the Socket.io website. From the guide:
Make sure you have Node along with npm installed
Perform an npm init to initialize your project
perform an npm install --save express
perform npm install --save socket.io
When you want to run your Node app, do node server.js
Here is an example of what a correctly-formatted Socket.io server file should look like:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Make sure you have this in your client HTML file:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>

Set up proxy server for create react app

I have started a react application using create-react-app and ran the npm run eject script to gain access to all files. I afterwards installed express and created server.js file that sits on same level as package.json file
these are server.js file contents:
const express = require('express');
const app = express;
app.set('port', 3031);
if(process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
}
app.listen(app.get('port'), () => {
console.log(`Server started at: http://localhost:${app.get('port')}/`);
})
Nothing crazy here, just setting up for future api proxies where I need to use secrets and as I don't want to expose my api.
after this I added a "proxy": "http://localhost:3001/" to my package.json file. I am now stuck as I need to figure out how to start my server correctly and use this server.js file in development mode and afterwards in production.
Ideally It would also be good if we could use more that one proxy i.e. /api and /api2
You didn't have to eject to run your server.js. You can just run it with node server.js together with create-react-app.
You can still do npm start even after ejecting to start your dev server.
To run /api1 and /api2, you just have to handle it in your server.js file and it should work just fine. You need to match the port in your server.js and the one in proxy settings inside package.json - in this case, it should be "proxy": "http://localhost:3031"

Run static website using node or grunt?

I am new to node or grunt. I have developed a website using html, css and bootstrap. Now I am confused how to run this site? shall I use nodejs to serve static files or use grunt?
Most of the examples I see use grunt-watch and grunt-serve to serve files. Is watching a file necessary only during development phase and not in production right?
I would also like to minify the files(css,js etc) before I host it. I am from java background where I normally use apache tomcat to deploy and run a webapp, but just for static site I don't want to use tomcat server. How do I go about this?
Note: I am trying to deploy my project on heroku.
As an addition to T.J. Crowder anwer
To serve static html app
npm install -g http-server
http-server ./index.html
To serve nodejs app
npm install -g forever
forever start server.js
To develop static app
//grunt or gulp
//both support watchers, livereaload, minifications, bundling
//google it
To develop nodejs app
express
hapi
meanjs
...many other
Finally got my answer:
Used express js to serve static files
use npm install express --save -dev
and then in the index.js or server.js file:
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.render('public/');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
So the above line app.use(express.static(__dirname + '/public')); will serve static files like html,css etc from this folder (i.e public)
and then in the command prompt: node index.js will start the server

Categories

Resources