How to run Express on io.js - javascript

So Node.js was forked late last year and the forked version is io.js.
I can't find anything of a setup guide on the docs. I'm fairly new, anyone know how I can setup io.js using Express web framework? Thanks!

Do the steps in answer 1, then create an index.js file like this
var express = require('express');
var app = express();
app.use('/resources', express.static(__dirname + '/resources'));
app.get('*', function (req, res, next) {
res.send('hello world');
res.end();
});
app.listen(3000);
and a package.json file like this
{
"name": "iojsexpress",
"version": "0.0.0",
"description": "Get express working with iojs",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.10.7"
}
}
and then run the following commands
npm install
iojs index.js
and visit localhost port 3000 in your browser and you should see "hello world"

Actually io.js wasn't released yet. First release will be at January 13th(or 14rth) (see here). At this time the best you can do to setup io.js is to clone its repository:
git clone https://github.com/iojs/io.js
and try to build it manually. On Unix/Max it looks like:
./configure
make
make install
But I do not recommend you to do this. Beware: now very active preparation for the first release is going on. Lots of commits with possibly breaking changes. So better wait less then one week until first official io.js version will be released.

Related

Azure App Service - Nodejs ES Module Error

Trying to host a simple nodejs api server on azure app service, but getting the following error when azure tries to deploy it
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\home\site\wwwroot\server.js
require() of ES modules is not supported.
require() of D:\home\site\wwwroot\server.js from D:\Program Files (x86)\iisnode\interceptor.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename server.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from D:\home\site\wwwroot\package.json.
Checked the azure app service, WEBSITE_NODE_DEFAULT_VERSION is set to ~14, and the installed nodejs version is v14.15.0 in the web app. Don't think this version of node has problem with import export anymore.
The code runs perfectly fine locally with either
node server.js
# or
node --experimental-modules server
Not sure why it is failing in azure
My code is below:
server.js
import express from 'express';
import bodyParser from 'body-parser';
let app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
let port = process.env.PORT || 8080;
let router = express.Router();
// Middleware to use for all requests
router.use(function(req, res, next) {
next();
});
router.get('/', function(req, res) {
res.json({ message: 'Default home page for the api!' });
});
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log(`Server up and running on port ${port}`);
package.json
{
"name": "my_package",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node --experimental-modules server",
"test": "mocha"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
}
However, if I change the import & export to require, then it will run in azure web app, it seems like perhaps azure iisnode is not compatible with emac6 yet? Anyone knows?
Anyone has any work around of this beside using babel to transpile emac6 down to emac5? As I have having some problem with executing and running the transpiled emac5 code.
Thankz
This can be solved by adding a new file next to your server.js and configuring it as the app service's (or more specifically iisnode's) entry point (see your web.config).
Let's call the new file run.cjs and put only the following line into it:
import("./server.js");
The cjs file extension is important because it tells Node that this file is not a ES module, as it would expect because of "type": "module" in your package.json. This allows other CommonJS files to include our new file - namely iisnode's interceptor.js.
It again imports the server.js which then runs fine as ES module.
Add "type": "module" in package.json file. It work for me.
{
"name": "module-error",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node --experimental-modules server",
"test": "mocha"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
},
"author": "",
"license": "ISC",
"type": "module"
}

Nodemon not reloading page

I am starting studying Node.js, so I am using nodemon to reload my page, but it's not working and already tried all Stack solutions aswell.
Look how simple is my code:
package.json
{
"name": "api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4"
},
"devDependencies": {
"nodemon": "^1.18.3"
}
}
server.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hey');
});
app.listen(3001);
My bash while interacting with res.send() message.
You are using nodemon with the server. It is restarting the server as you make changes to the server.js file. That is, your endpoints are being updated. This will not cause your client to reload. As you are simply navigating to the endpoint that you are creating within the browser, you will not see the changes reflected without refreshing.
That isn't to say that there is no benefit to running nodemon in this way. If you were not doing so you would need to also close the node instance (ctrl-c) and then rerun it every time before refreshing the page. Otherwise, you would still be running the old version of your server and still see the same content served.
Eventually you will consume these endpoints using an http client from your client application, this is generally when you take advantage of a hot reloading environment. There are some options here if you want to make express live-reload before then.

Nodemon keeps restarting server

I have an express server that uses a local json file for a database. I'm using https://github.com/typicode/lowdb for getters and setters.
Currently the server keeps starting and restarting without any problems, but can't access it. Below is my Server.js file:
import express from 'express'
import session from 'express-session'
import bodyParser from 'body-parser'
import promisify from 'es6-promisify'
import cors from 'cors'
import low from 'lowdb'
import fileAsync from 'lowdb/lib/storages/file-async'
import defaultdb from './models/Pages'
import routes from './routes/index.js'
const app = express();
const db = low('./core/db/index.json', { storage: fileAsync })
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', routes);
app.set('port', process.env.PORT || 1337);
db.defaults(defaultdb).write().then(() => {
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
});
Anyone have an issue like this before? I think it has something to do with this line:
db.defaults(defaultdb).write().then(() => {
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
});
From the documentation:
nodemon will watch the files in the directory in which nodemon was started, and if any files change, nodemon will automatically restart your node application.
If your db's .JSON file is under the watch of nodemon, and you're constantly writing to it, your server will restart in an infinite loop thus making it inaccessible. Try moving your .JSON file outside the scope of nodemon's watch via moving it outside your directory or via some nodemon configuration (if possible).
I solved this issue from this page.
practically you just have to do
nodemon --ignore 'logs/*'
Update: the link was hijacked and has been removed.
My solution: I've added nodemonConfig in package.json file in order to stop infinite loop/restarting. In package.json:
"nodemonConfig": { "ext": "js", "ignore": ["*.test.ts", "db/*"], "delay": "2" },
"scripts": { "start": "nodemon" }
I was puzzled by a constant stream of restarts. I started with nodemon --verbose to see what was causing the restarts.
This revealed that my package.json file was the culprit. I was running my installation in a Dropbbox folder and had just removed all files from my node_modules folder and done a fresh install. Another computer that shared my Dropbox folder was running at the time, and unknown to me, it was busily updating its node_module files and updating the Dropbox copy of package.json files as it did so.
My solution turned out to be simple, I took a break and waited for Dropbox to finish indexing the node_modules folder. When Dropbox finished synching, nodemon ran without any unexpected restarts.
In my case (which is the same as the OP) just ignoring the database file worked
nodemon --ignore server/db.json server/server.js
You can use this generalized config file.
Name it nodemon.json and put in the root folder of your project.
{
"restartable": "rs",
"ignore": [".git", "node_modules/", "dist/", "coverage/"],
"watch": ["src/"],
"execMap": {
"ts": "node -r ts-node/register"
},
"env": {
"NODE_ENV": "development"
},
"ext": "js,json,ts"
}
I solved this by adding the following code to the package.json file
"nodemonConfig": {
"ext": "js",
"ignore": [
"*.test.ts",
"db/*"
],
"delay": "2"
}
}
Add this in your package.json:
"nodemonConfig": {
"ext": "js",
"ignore": [
"*.test.ts",
"db/*"
],
"delay": "2"
}
I solved this by creating a script in my package.json like this:
scripts": {
"start-continuous": "supervisor server/server.js",
},
This will work if you have supervisor installed in your global scope.
npm install supervisor -g
Now all I do is: npm run start-continuous

Nodemon not refreshing browser in React-Express-Node App

I have installed nodemon locally in my workspace, but even though it restarts in the terminal after changes are made, it does not refresh the browser page. I have to manually refresh it each time.
I've got Express, Node, React and Webpack running in the environment.
This is how my setup looks like -
My package.json starts up server.js -
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js"
},
and server.js is -
var express = require('express');
var app = express();
app.use(express.static('public'));
app.listen(3000, function () {
console.log("Express server is up on port 3000");
});
The entry point in the webpack config file is -
module.exports = {
entry: './public/scripts/app.jsx',
output: {
path: __dirname,
filename: './public/scripts/bundle.js'
}
What should I do to fix it?
Update -
I made a video to describe the situation, if it helps.
nodemon is only for restarting the server when your server code changes. It has no functionality to reload your page in the browser. If you want automatic browser reload, you could, for example, run a webpack dev server in addition to your nodemon. webpack dev server is able reload the page in the browser when your client code changes, it can even update the page in the browser without a full page reload, if you use its hot module reloading feature.
in package.json
"scripts": {
"start": "nodemon server.js -e html,js,css"
},
in server js
var reload = require('reload')
app.listen(3000, () => {
console.log(`Listening on port 3000`);
})
reload(app);
in index.html
<body>
<h1>ron</h1>
<script src="/reload/reload.js"></script> <!-- it's necessary -->
</body>
For those needing to use nodemon and reload browser on change as well, I replied here https://stackoverflow.com/a/51089425/7779953
Solution is Nodemon + Browser Sync + Gulp + Express server

Failed to load resource socket.io in nodejitsu?

I'm trying to deploy a simple chat applicacion in Nodejitsu, and using socket.io.
I use the application localy and it works perfectly but when I deploy to nodejitsu I get the following error in the javascript console:
Failed to load resource
And the chat doesnt work.
I checked to the source code and clicked in the
/socket.io/socket.io.js
and it works perfectly
My package.json is:
{
"name": "Chat_1",
"subdomain": "Chat_1",
"scripts": {
"start": "node main.js"
},
"version": "0.0.0-4",
"engines": {
"node": "0.10.x"
},
"dependencies": {
"socket.io": "*"
}
}
I hope someone could help me, please!
According to the Nodejitsu Handbook "We reroute all traffic to port 80". Double check you're using port 80.
server.listen(80);

Categories

Resources