I am running through the Hello World app tutorial in GCP. And I am getting stuck at the server.js step.
The code of the server.js is as below:
'use strict';
const mongodb = require('mongodb');
const http = require('http');
const nconf = require('nconf');
let uri = 'mongodb+srv://my_name:<mypassword>#mydatabase-clr75.gcp.mongodb.net/test?retryWrites=true&w=majority';
if (nconf.get('mongoDatabase')) {
uri = `${uri}/${nconf.get('mongoDatabase')}`;
}
console.log(uri);
mongodb.MongoClient.connect(uri, (err, db) => {
if (err) {
throw err;
}
// Create a simple little server.
http.createServer((req, res) => {
if (req.url === '/_ah/health') {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('OK');
res.end();
return;
}
const collection = db.collection('Messages');
var datetime = new Date();
const msg = {
msgDescription: '\nHello World received on ' + datetime
};
collection.insert(msg, (err) => {
if (err) {
throw err;
}
// push out a range
let msglist = '';
collection.find().toArray((err, data) => {
if (err) {
throw err;
}
data.forEach((msg) => {
msglist += `${msg.msgDescription}; `;
});
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.write('Messages received so far:\n');
res.end(msglist);
});
});
}).listen(process.env.PORT || 8080, () => {
console.log('started web process');
});
});
I receive the error as below:
mongodb+srv://my_name:#mydatabase-clr75.gcp.mongodb.net/test?retryWrites=true&w=majority
/home/herboratory/node_modules/mongodb/lib/url_parser.js:19
throw new Error('invalid schema, expected mongodb');
^ Error: invalid schema, expected mongodb
at module.exports (/home/herboratory/node_modules/mongodb/lib/url_parser.js:19:11)
at connect (/home/herboratory/node_modules/mongodb/lib/mongo_client.js:486:16)
at Function.MongoClient.connect (/home/herboratory/node_modules/mongodb/lib/mongo_client.js:250:3)
at Object. (/home/herboratory/server.js:12:21)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! test#1.0.0 start: node
server.js npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the
test#1.0.0 start script. npm ERR! This is probably not a problem with
npm. There is likely additional logging output above. npm ERR! A
complete log of this run can be found in: npm ERR!
/home/herboratory/.npm/_logs/2019-06-26T03_58_26_823Z-debug.log
I was wondering it should be the format error after reading some other posts here with the same error line, so I've tried '...', "..." and without any quotation mark but still remain error. Would please guide me where's the error?
Except for the URI, is there anywhere else I also need to modify inside the code? As far as I know from the instruction I just need to insert my own Atlas Connection string.
Many thanks.
The error invalid schema, expected mongodb means that you're using an outdated node driver version. The old driver cannot parse the new mongodb+srv URI scheme.
Support for the mongodb+srv scheme was added in the node driver version 3.0 in this ticket: NODE-1145.
Upgrade your node driver using:
$ npm install mongodb
and the error should go away.
I had the same error. The problem was with setup in mongoDB Atlas and setup in my Application.
In mongoDB Atlas:
Create DATABASE and COLLECTION
Create Database User
Add your IP Address (public) in IP Whitelist, Network Access
Example of my solution:
File .env
MONGO_URI=mongodb+srv://jmendoza:your-password#cluster0-7rxkw.mongodb.net/nodeapi?retryWrites=true&w=majority
PORT=3000
File app.js
const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const { postRoutes } = require('./routes/posts');
const app = express();
const port = process.env.PORT || 3000;
dotenv.config();
// BD
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('mongoDB, Atlas. Connected'))
.catch((err) => console.error(err));
// Middleware
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(expressValidator());
// Routes
app.use('/api/v1', postRoutes);
app.listen(port, () => {
console.log(`A NodeJS API is listining on port: ${port}`);
});
File package.json
{
"name": "node-api",
"version": "1.0.0",
"description": "A NodeJS API",
"main": "app.js",
"scripts": {
"dev": "nodemon app.js"
},
"keywords": [
"node",
"api"
],
"author": "Jonathan Mendoza",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^5.3.1",
"mongoose": "^5.9.7",
"morgan": "^1.9.1",
"nodemon": "^2.0.3"
}
}
Running application (console)
jmendoza#jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ npm run dev
> node-api#1.0.0 dev /home/jmendoza/IdeaProjects/NodeJS-API-Course/Basic-Node-API
> nodemon app.js
[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
mongoDB, Atlas. Connected
NodeJS Version
jmendoza#jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ node -v
v13.12.0
You can see my full code on GitHub:
https://github.com/JonathanM2ndoza/NodeJS-API-Course/tree/master/Basic-Node-API
Related
I'm running into an issue where I try to require a .jpg image.
When Googling I thought it had something to do with Jest but now when I start from a clean project, not having Jest as a dependency I get the same error.
What can be the issue?
This is the files I'm trying to run
server.js
// Import express framework
const express = require('express')
// Import routes
const visionAiRouter = require('./routes/vision-ai-route')
// Setup default port
const PORT = process.env.PORT || 4000
// Create express app
const app = express()
// Vision AI Route
app.use('/ai', visionAiRouter)
// Implement route for errors
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
// Start express app
app.listen(PORT, function() {
console.log(`Server is running on: ${PORT}`)
})
vision-ai-route.js
// Import
const express = require('express')
const visionAi = require('../controllers/vision-ai-controller')
// Create express router
const router = express.Router()
router.get('/', visionAi.labelDetection)
// Export
module.exports = router
vision-ai-controller.js
// Assets
const cat = require('./../data/cat.jpg')
// Create controller for GET request to '/users/all'
exports.labelDetection = async (req, res) => {
// Imports the Google Cloud client library
const vision = require('#google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
const [result] = await client.labelDetection(cat);
const labels = result.labelAnnotations;
const stringify = JSON.stringify(labels);
await res.json(stringify)
}
package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"#google-cloud/vision": "^2.1.1",
"express": "^4.17.1",
"nodemon": "^2.0.4"
},
"devDependencies": {},
"scripts": {
"start": "nodemon server.js"
},
"author": "",
"license": "ISC"
}
Stacktrace
/Users/kod/Desktop/Code/Private/vision-ai/test/data/cat.jpg:1
����
^
SyntaxError: Invalid or unexpected token
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (/Users/kod/Desktop/Code/Private/vision-ai/test/controllers/vision-ai-controller.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
You can't require a non-code file as require is meant to load executable code. The correct equivalent would be const cat = fs.readFileSync('./test/data/cat.jpg').
I am trying to deploy a NodeJS live streaming server which works on heroku built on rtmp server using node-media-server and socket.io. I am facing issue in starting the node-media-server since it needs 2 ports to run as per config format:
const NodeMediaServer = require('node-media-server');
const config = {
rtmp: {
port: 1935,
chunk_size: 60000,
gop_cache: true,
ping: 30,
ping_timeout: 60
},
http: {
port: 8000,
allow_origin: '*'
}
};
var nms = new NodeMediaServer(config)
nms.run();
I've tried deploying app on new heroku app by following official guide. Since Heroku provides only one port per dyno, it gives me these logs on my heroku app dashboard:
2020-04-07T23:08:24.289041+00:00 app[web.1]: 4/7/2020 23:08:24 23 [ERROR] Node Media Trans Server startup failed. ffmpeg:/usr/local/bin/ffmpeg cannot be executed.
2020-04-07T23:08:24.290753+00:00 app[web.1]: (node:23) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
2020-04-07T23:08:24.291397+00:00 app[web.1]: listening on port 19586
2020-04-07T23:08:24.292059+00:00 app[web.1]: 4/7/2020 23:08:24 23 [ERROR] Node Media Rtmp Server Error: listen EADDRINUSE: address already in use :::19586
2020-04-07T23:08:24.292694+00:00 app[web.1]: 4/7/2020 23:08:24 23 [ERROR] Node Media Http Server Error: listen EADDRINUSE: address already in use :::19586
2020-04-07T23:08:24.293383+00:00 app[web.1]: 4/7/2020 23:08:24 23 [ERROR] Node Media WebSocket Server Error: listen EADDRINUSE: address already in use :::19586
2020-04-07T23:08:24.682440+00:00 heroku[web.1]: State changed from starting to up
2020-04-07T23:08:24.693405+00:00 app[web.1]: Connected to the database
I need to know how I can deploy my app on heroku (or any other alternative) to make it available in production mode. My server works fine on my MacBook Pro.
Here's my code:
const { NodeMediaServer } = require('node-media-server');
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const http = require('http');
const fs = require('fs');
const bodyParser = require('body-parser');
const path = require('path');
const process = require('process')
const port = process.env.PORT||5000
const port2 = process.env.PORT||8000
const port3 = process.env.PORT||8001
const server = http.createServer(app);
const io = require('socket.io').listen(server);
require('./app/controllers/socketIO')(io);
mongoose.Promise = global.Promise;
global.appRoot = path.resolve(__dirname);
mongoose.connect(
"mongodb://databasecredentials",
{ useNewUrlParser: true },
err => {
if (err) {
console.log(err);
} else {
console.log('Connected to the database');
}
}
);
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.json());
app.set('socketio', io);
app.set('server', server);
app.use(express.static(`${__dirname}/public`));
server.listen(port, err => {
if (err) {
console.log(err);
} else {
console.log(`listening on port ${port}`);
}
});
const nodeMediaServerConfig = {
rtmp: {
port: port2,
chunk_size: 60000,
gop_cache: true,
ping: 60,
ping_timeout: 30
},
http: {
port: port3,
mediaroot: './media',
allow_origin: '*'
},
trans: {
ffmpeg: '/usr/local/bin/ffmpeg',
tasks: [
{
app: 'live',
ac: 'aac',
mp4: true,
mp4Flags: '[movflags=faststart]'
}
]
}
};
var nms = new NodeMediaServer(nodeMediaServerConfig);
nms.run();
I'm not very familiar with Heroku, but in the first line of the logs it states:
[ERROR] Node Media Trans Server startup failed. ffmpeg:/usr/local/bin/ffmpeg cannot be executed.
you need to install ffmpeg on the machine running the code. This is the first step to get your server starting (this might not fix all the problems you're having but this is the first thing you need to start with).
I'm trying to do something similar using GCP. In order to get it to run, I created a package.json file and set the start script to apt install --fix-missing --assume-yes ffmpeg && node app.js as a temporary workaround:
{
"name": "app-service-hello-world",
"description": "Simple Hello World Node.js sample for Azure App Service",
"version": "0.0.1",
"private": true,
"license": "MIT",
"author": "Microsoft",
"scripts": {
"start": "apt install --fix-missing --assume-yes ffmpeg && node app.js"
},
"dependencies": {
"node-media-server": "^2.1.9"
}
}
This might help you adding ffmpeg correctly to your Heroku environment: Install FFMPEG on Heroku
I am trying to create a Full Stack Node & Vue application that takes data from an API. I am running into an issue where I am trying to run both the client and server concurrently but the code is running into an error. Please bear with me if I am structuring this question wrong as I am still fairly new to coding!
This is the following error log:
[0] Error occurred when executing command: npm run server
[0] Error: spawn cmd.exe ENOENT
[0] at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
[0] at onErrorNT (internal/child_process.js:469:16)
[0] at processTicksAndRejections (internal/process/task_queues.js:84:21)
[1] Error occurred when executing command: npm run client
[1] Error: spawn cmd.exe ENOENT
[1] at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
[1] at onErrorNT (internal/child_process.js:469:16)
[1] at processTicksAndRejections (internal/process/task_queues.js:84:21)
[1] npm run client exited with code -4058
[0] npm run server exited with code -4058
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! apex-tracker#1.0.0 dev: `concurrently "npm run server" "npm run client"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the apex-tracker#1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
From what I can tell the program is running fine up until it reaches the "dev" script in my package.json:
{
"name": "apex-tracker",
"version": "1.0.0",
"description": "Apex Legends user statistics tracker",
"main": "server.js",
"scripts": {
"start": "node server",
"server": "nodemon server",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "Jared Mackay",
"license": "MIT",
"dependencies": {
"concurrently": "^5.0.1",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"morgan": "^1.9.1",
"node-fetch": "^2.6.0"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
prior to the errors, the program ran fine when I ran the npm run server command, however upon installing the client folder and adding the client and dev script that's when I ran into my errors.
Here is my server.js that I am trying to run with the client:
const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
//Load configuration file
dotenv.config({ path: './config.env' })
const app = express();
//Develper logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
//Profile routes
app.use('/api/v1/profile', require('./routes/profile'));
const port=process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server running on ${process.env.NODE_ENV} mode on port ${port}`);
});
I've tried clearing the npm cache, deleting and reinstalling node-modules as well as package-lock.json, but this created more issues rather than fixing them. I had to revert back to an old git commit and now I'm stuck.
I don't think this route .js file is an issue but here it is just in case profile.js:
const express = require('express');
const router = express.Router();
const fetch = require('node-fetch');
router.get('/:platform/:gamertag', async (req, res) => {
try {
const headers = {
'TRN-Api-Key': process.env.TRACKER_API_KEY
}
const { platform, gamertag } = req.params;
const response = await fetch(
`${process.env.TRACKER_API_URL}/profile/${platform}/${gamertag}`,
{
headers
}
);
const data = await response.json();
if(data.errors && data.errors.length > 0) {
return res.status(404).json({
message: 'Profile Not Found'
});
}
res.json(data);
} catch (err) {
console.error(err);
res.status(500).json({
message: 'Server Error'
});
}
});
module.exports = router;
Thank you in advance!
spawn cmd.exe ENOENT
Your program does not know where to find cmd.exe.
This problem has probably been posted about a dozen times, but I can't find a single fix to my problem.
Here is my code:
//////////////////// VARIABLES ////////////////////
//use express
var express = require('express');
//variable to use express
var app = express();
//use the body-parser middleware to handle post data
var bodyParser = require('body-parser');
//create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//create a variable for the server
//var server = require('http').Server(app)//
//////////////////// SETUP ////////////////////
//tells express to use ejs as the view/template engine
app.set('view engine', 'ejs');
//use express as middleware to serve static pages
app.use('/CSS', express.static('CSS'));
app.use('/images', express.static('images'));
//////////////////// FUNCTIONALITY ////////////////////
//sets index as the default page
app.get('/', function (req, res) {
res.render('index');
});
//serve specified pages
app.get('/:page', function (req, res) {
res.render(req.params.page);
});
app.post('/custom_rec', urlencodedParser, function (req, res) {
console.log(req.body);
res.render('custom_rec', {data: req.body});
});
const host = '0.0.0.0';
const port = process.env.PORT || 5000;
app.listen(port, host, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
Here are the relevant logs:
2018-10-23T08:42:25.388218+00:00 heroku[web.1]: State changed from crashed to starting
2018-10-23T08:42:30.109913+00:00 heroku[web.1]: Starting process with command `node ./index.js`
2018-10-23T08:42:33.503841+00:00 heroku[web.1]: Process exited with status 1
2018-10-23T08:42:33.525464+00:00 heroku[web.1]: State changed from starting to crashed
2018-10-23T08:42:33.439948+00:00 app[web.1]: module.js:549
2018-10-23T08:42:33.439965+00:00 app[web.1]: throw err;
2018-10-23T08:42:33.439967+00:00 app[web.1]: ^
2018-10-23T08:42:33.439968+00:00 app[web.1]:
2018-10-23T08:42:33.439970+00:00 app[web.1]: Error: Cannot find module '/app/index.js'
2018-10-23T08:42:33.439972+00:00 app[web.1]: at Function.Module._resolveFilename (module.js:547:15)
2018-10-23T08:42:33.439973+00:00 app[web.1]: at Function.Module._load (module.js:474:25)
2018-10-23T08:42:33.439975+00:00 app[web.1]: at Function.Module.runMain (module.js:693:10)
2018-10-23T08:42:33.439976+00:00 app[web.1]: at startup (bootstrap_node.js:191:16)
2018-10-23T08:42:33.439978+00:00 app[web.1]: at bootstrap_node.js:612:3
Here is my Procfile:
web: node ./index.js
Here is my package.json:
{
"name": "anirec",
"version": "1.0.0",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "hidden"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "hidden"
},
"homepage": "hidden",
"description": "",
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.6.1",
"express": "^4.16.4"
},
"engines": {
"node": "8.11.4"
}
}
Here is an image of my directory:
The app works using local host.
I've tried having my server listen to 'process.env.PORT'. I've tried taking out "main" in my package.json. I've tried a relative path in my Procfile. I've tried reinstalling node_modules. My Procfile is in the same directory as index.js.
What else am I missing? Thanks in advance.
Edit: I've also tried restarting the server/dyno. 'Index.js' is also listed when I type 'git ls-files' into my terminal.
You have case-sensitive issue, your Index.js starts with capital letter, it should be index.js instead.
I am trying to setup my Nodejs/Express hosting server to have multiple applications (Sails.js app type) running on my VPS but I got this error :
/srv/data/web/vhosts/default/node_modules/vhost/index.js:78
throw new TypeError('argument server is unsupported')
^
TypeError: argument server is unsupported
at createHandle (/srv/data/web/vhosts/default/node_modules/vhost/index.js:78:9)
at vhost (/srv/data/web/vhosts/default/node_modules/vhost/index.js:39:16)
at Object.<anonymous> (/srv/data/web/vhosts/default/server.js:46:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
Of course I previously installed all my dependencies.
My Nodejs/Express base configuration for multiple apps is good because it works fine with this express vhosts example configuration:
https://github.com/loicsaintroch/express-vhosts
So here my nodejs server app structure:
.../vhosts/default/server.js
package.json
/app1
/app.js
/app2
/app.js
/app3
/app.js
And here my server.js file based on this previous github example:
// Module dependencies
var express = require('express');
var vhost = require('vhost');
var app = express();
// vhosts
app
.use(vhost('app1.com', require('./app1/app.js')))
.listen(8080);
And the package.json file:
{
"name": "default",
"private": true,
"version": "0.0.1",
"description": "Default git repository for some web applications.",
"dependencies": {
"express": "^4.2.0",
"vhost": "^2.0.0",
"forever": "^0.11.1",
"static-favicon": "^1.0.0",
"ejs": "^1.0.0",
"morgan": "^1.0.0",
"cookie-parser": "^1.0.1",
"body-parser": "^1.0.0",
"debug": "^0.7.4"
},
"scripts": {
"start": "forever start server.js --prod",
"debug": "node debug server.js"
},
"main": "server.js"
}
Error come from vhost npm package:
/**
* Create handle to server.
*
* #param {function|Server} server
* #return {function}
* #api private
*/
function createHandle(server){
if (typeof server === 'function') {
// callable servers are the handle
return server
} else if (typeof server.emit === 'function') {
// emit request event on server
return function handle(req, res) {
server.emit('request', req, res)
}
}
throw new TypeError('argument server is unsupported')
}
OK here precisely I think vhost package has a problem with the app.js response from sails.js framework. Here the app.js file content from my Sails.js app:
/**
* app.js
*
* Use `app.js` to run your app without `sails lift`.
* To start the server, run: `node app.js`.
*
* This is handy in situations where the sails CLI is not relevant or useful.
*
* For example:
* => `node app.js`
* => `forever start app.js`
* => `node debug app.js`
* => `modulus deploy`
* => `heroku scale`
*
*
* The same command-line arguments are supported, e.g.:
* `node app.js --silent --port=80 --prod`
*/
// Ensure a "sails" can be located:
(function() {
var sails;
try {
sails = require('sails');
} catch (e) {
console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.');
console.error('To do that, run `npm install sails`');
console.error('');
console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.');
console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,');
console.error('but if it doesn\'t, the app will run with the global sails instead!');
return;
}
// Try to get `rc` dependency
var rc;
try {
rc = require('rc');
} catch (e0) {
try {
rc = require('sails/node_modules/rc');
} catch (e1) {
console.error('Could not find dependency: `rc`.');
console.error('Your `.sailsrc` file(s) will be ignored.');
console.error('To resolve this, run:');
console.error('npm install rc --save');
rc = function () { return {}; };
}
}
// Start server
sails.lift(rc('sails'));
})();
==============================================
UPDATE: FULL SOLUTION EXAMPLE
As a synthesis of the great answer I wrote a complete case study available here
https://github.com/migswd/express-sails-vhosts
==============================================
The problem here is that you're trying to shoehorn an example meant for Express apps to work with Sails apps.
If you look at the app.js files from the example vhost apps, they all use module.exports to return an Express app instance. The app.js from the Sails app you posted clearly does no such thing; it doesn't export anything at all. Furthermore, that file is calling sails.lift, which starts its own server listening on port 1337.
A little elbow grease can get this to work. Instead of lifting the Sails app, you can use sails.load which does everything except start listening on a port. This is an asynchronous method, so it'll require a reworking of your server.js as well.
The Sails app.js files become:
var sails = require('sails');
module.exports = function(cb) {
process.chdir(__dirname);
sails.load(cb);
};
Every running sails instance exposes its underlying Express app as .hooks.http.app, so in your server.js, use async or something similar to load all of the Sails apps, then hook them up with vhost:
// Module dependencies
var express = require('express');
var vhost = require('vhost');
var app = express();
var async = require('async');
async.auto({
app1: require('./app1/app.js'),
app2: require('./app2/app.js'),
app3: require('./app3/app.js')
}, function doneLoadingApps(err, apps) {
app
.use(vhost('app1.io', apps.app1.hooks.http.app))
.use(vhost('app2.io', apps.app2.hooks.http.app))
.use(vhost('app3.io', apps.app3.hooks.http.app))
// Mix in a vanilla Express app as well
.use(vhost('app4.io', require('./app4/app.js')))
.listen(8080);
});