Jade cache template and Node restart - node.js

My setup:
Express 4.2.0
Jade 1.3.1
I'm learning express and jade templating.
I have a view, mypage, which display name and age vars defined in the route below.
Everytime I change the options args of render (changing name or age to anything), the mypage view doesn't get updated when I reload. So I always have to restart the node app (killing with ctrl+C and npm start) to get the last update.
It seems like it's caching, but I'm in development mode.
/* GET my page */
router.get('/mypage', function(req, res){
res.render('mypage', {
name: 'Default John',
age: 213456
});
});
I tried app.disable('view cache') and nothing. Is this the expected behavior?

Try to use
app.set('view cache', true);

Related

ExpressJS controller not being called

I have a route that calls my controller and the controller does nothing but respond with a view. Nothing dynamic happening here. I am using Swig for my views. For some reason, my view is not getting refreshed with the new changes. it still shows me the old view. I have tried the following to no avail:
app.set('view cache', false);
// To disable Swig's cache, do the following:
swig.setDefaults({ cache: false });
app.disable('view cache');
app.set('etag', 'strong');
I have a console.log statement in my controller and it never seems to log anything out leading me to believe that that controller is never called. I do have a simple middleware that logs the path out before the routes are set up and I see the request for my route but the controller never gets called and an older version of the template view is served.
Am I missing something??
Update: Server controller code:
exports.index = function (req, res) {
res.render('myapp', {});
};
In order to check your code without node.js restart, consider to use pm2 or nodemon
After installation of pm2:
pm2 start app.js --watch
PM2 automatically restarts your app when a file changes in the current directory or its subdirectories.
But my favorite choice is nodemon:
nodemon [your node app]

Node starts my server, so does gulp, but gulp doesn't find any paths

I am sure this is something small, but I am unable to figure it out. Node, nodemon and gulp use app.js to start my server so I am not sure why one way works while gulp does not. If I start my server using:
nodemon app.js or
node app.js it starts fine and when I use the path localhost:1337 in the browser it does what it is supposed to do.
When I use the command:
gulp
it says that it started the server but when I navigate to localhost:1337 it does not display anything other than "Cannot GET /" and none of my sources are showing in the inspector. I still get the message that "the port is listening" as indicated in my app.js console.log. My gulpfile is as follows:
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
gulp.task('nodemon', function(){
nodemon({
script: './app/app.js'
})
});
gulp.task('watch', function(){
gulp.watch('*.js', ['nodemon']);
});
gulp.task('default', ['nodemon']);
my app.js file is:
express = require('express');
var app = express();
app.use(express.static('../views'));
app.use(express.static('../bower_components/angular'));
app.use(express.static('./directives'));
app.listen(1337);
console.log("The port is listening");
The 'Cannot GET /' being displayed when you go to localhost:1337 is Express's generic message when a request is made against a route that is undefined. A route needs to be defined for the pages that you want to serve. You need to add a Route to handle the request to the root of your app at http://localhost:1337/.
app.get('/', function(req, res) {
// return back a message
res.send('Welcome!');
});
Place the above snippet above app.listen() and the message "Welcome!" will be displayed.
To serve a view in an html file you need to add a view engine so Express knows how to render the file. Additionally, the views property needs to be configured so Express knows where to render your views from. The example below uses ejs to just handle plain html files and not worry about a template engine like jade.
app.use('views', path.join(__dirname + '/views'));
app.engine('html', require('ejs').renderFile);
app.use('view engine', 'html');
Now we can use the render function on the res object to send our index.html file:
app.get('/', function(req, res) {
res.render('index');
});
This a guide from ExpressJS on how to implement routing in Express.

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.

Angular / Express hosting

I want to run angular on a linux box without needing node or express. I've created a website but not sure what tech is what, haha. I'm assuming I have a simple web server using express server, see code below.
var express = require ('express');
var app = express();
var path = require('path');
app.use(express.static(__dirname + '/'));
app.listen(8080);
console.log('Magic happens on port 8080');
I start this using the node server command. And the rest of the code is angular-ui.
Do I need to use express (and host this on a node compatible server), or can I just run this thing on a linux box without express? If so, do i need to replace my server.js file (above) with something else? or... Currently it's not working on the linux box, but works locally just fine.
**Edit: I tested an angular 'hello world' app on my shared server, it worked fine. When I run the full angular app on the shared server I get the following error:
Uncaught Error: [$injector:modulerr] Failed to instantiate module routerApp due to:
Error: [$injector:nomod] Module 'routerApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
** edit: In answer to #RobertMoskal 's question below, the angular hello world test that's working on the shared server is basically this:
<input ng-model="name" type="text" placeholder="Type a name here">
<h1>Hello {{ name }}</h1>
And the real app is basically something like this, using ui-view and ng-repeat in the html:
var routerApp = angular.module('routerApp', ['ui.router']);
routerApp.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/home');
$locationProvider.html5Mode(false).hashPrefix("");
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
templateUrl: 'partial-home.html',
// onEnter: scrollContent
})
// ANIMATION AND NESTED VIEWS ========================================
.state('animation', {
url: '/animation',
templateUrl: 'partial-anim.html',
controller: function($scope) {
$scope.animations = [
{ title:'One', url:'http://yahoo.com', bg:'#f8f8f8', width:'160', height:'600', imageAsset:'assets/imgs/web/MyWebsites_1.jpg', paragraph:'some text of some description'},
{ title:'Two', url:'http://google.com', bg:'#f8f8f8', width:'160', height:'600', imageAsset:'assets/imgs/web/MyWebsites_2.jpg', paragraph:'rabbit rabbit rabbit'},
{ title:'Three', url:'http://bambam.com', bg:'#f8f8f8', width:'160', height:'600', imageAsset:'assets/imgs/web/MyWebsites_3.jpg', paragraph:'blahiblahblah'}];
}
})
// GAME VIEWS ========================================
.state('game', {
url: '/game',
templateUrl: 'partial-game.html'
})
// CONTACT VIEWS ========================================
.state('contact', {
url: '/contact',
templateUrl: 'partial-contact.html'
})
});
You need some web server to server your angular app as a "static" asset. This can be apache or nginx or any number of web servers. Most linux distributions make it easy to install them.
You can also go super lightweight with the built in python web server:
cd /var/www/
$ python -m SimpleHTTPServer
You can even host your application for free on github.
In all cases you you just need to make sure that the web server is serving your assets from the correct path. The above python example example you might have your app entry point in /var/www/index.html and it would be served as http://localhost:8000/index.html.

Unable to get connect-livereload to work with express server in gulp task

I am working off of Yeoman's gulp-webapp generator. I have modified my gulp serve task to use my Express server, rather than the default connect server it ships with. My issue is with Livereload functionality. I am trying to simply port the connect-livereload to work with my Express server rather than having to install new dependencies. It's to my understanding that most connect middleware should work fine with Express, so I am assuming connect livereload is compatible with Express 4.
Here are the contents of the relevant tasks in my gulpfile:
gulp.task('express', function() {
var serveStatic = require('serve-static');
var app = require('./server/app');
app.use(require('connect-livereload')({port: 35729}))
.use(serveStatic('.tmp'));
app.listen(3000);
});
gulp.task('watch', ['express'], function () {
$.livereload.listen();
// watch for changes
gulp.watch([
'app/*.ejs',
'.tmp/styles/**/*.css',
'app/scripts/**/*.js',
'app/images/**/*'
]).on('change', $.livereload.changed);
gulp.watch('app/styles/**/*.css', ['styles']);
gulp.watch('bower.json', ['wiredep']);
});
gulp.task('styles', function () {
return gulp.src('app/styles/main.css')
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe(gulp.dest('.tmp/styles'));
});
gulp.task('serve', ['express', 'watch'], function () {
require('opn')('http://localhost:3000');
});
With this simple setup, when I run gulp serve in my cmd everything spins up fine and I can accept requests at http://localhost:3000.
Now if I go and change the body's background color from #fafafa to #f00 in main.css and hit save, my gulp output will respond with main.css was reloaded, as seen in the bottom of this screenshot.
However, my webpage does not update. The background color is still light-grey instead of red.
Is there perhaps a conflict between my express server config and the way gulp handles its files? Is my Express server forcing the use of app/styles/main.css rather than the use of .tmp/styles/main.css? Shouldn't the livereload script handle the injection of the new temporary file?
Thanks for any help.
EDIT:
I was able to move forward a bit by adding livereload.js to the script block of my index file, like so:
<script src="http://localhost:35729/livereload.js"></script>
I am now able to get live changes pushed to the client. Why was this file not getting injected before? How can I ensure this is getting used programatically as opposed to pasting it into my files?
I was able to get past this issue by removing the app.use(require('connect-livereload')({port: 35729})) from my gulpfile, along with a couple of other lines, and having that instantiate in my Express server's app.js file.
My gulpfile's express task now looks like this:
gulp.task('express', function() {
var app = require('./server/app');
app.listen(3000);
});
I added in the connect-livereload just above where I specify my static directory in Express:
if (app.get('env') === 'development') {
app.use(require('connect-livereload')());
}
app.use(express.static(path.join(__dirname, '../app')));
Once I started using this setup, I was getting the livereload.js script injected into my document, and client-side changes are now auto-refreshed just how I wanted.
Hope this helps someone!

Resources