How to restart node server on file change - javascript

I'm developing a node/express app
$> ./node_modules/babel/bin/babel-node.js index.js
Now I would like to reload the application if I make changes to index.js or any other dependency. How can I do this. I guess I have to use gulp for this, but than still I would like to have some advice on how to do this (which modules to use ect)
UPDATE: I've just tested with supervisor, but when something changes I get the following error:
$> /node_modules/.bin/supervisor --exec ./node_modules/babel/bin/babel-node.js index.js
crashing child
Starting child process with './node_modules/babel/bin/babel-node.js index.js'
events.js:85
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at exports._errnoException (util.js:746:11)
at Server._listen2 (net.js:1146:14)
at listen (net.js:1172:10)
at Server.listen (net.js:1257:5)
UPDATE: I just tried nodemon but I get the same errors as with supervisor:
$> nodemon --exec ./node_modules/babel/bin/babel-node.js index.js --watch libs
...
22 Aug 16:58:35 - [nodemon] restarting due to changes...
22 Aug 16:58:35 - [nodemon] starting `./node_modules/babel/bin/babel- node.js index.js`
events.js:85
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at exports._errnoException (util.js:746:11)
at Server._listen2 (net.js:1146:14)
at listen (net.js:1172:10)
UPDATE: I've solved the EADDRINUSE issue by adding the following to index.js
process.on('exit', () => {
server.close();
})
process.on('uncaughtException', () => {
server.close();
})
process.on('SIGTERM', () => {
server.close();
})
However, now it seems to restart, but the new code is not loaded

use this:
supervisor -- -r 'babel/register' index.js
and remove server.close code.

I was really disappointed with the performance of all the solutions where you run babel-node within nodemon (or supervisor). So I built this:
https://github.com/kmagiera/babel-watch
You can use it as follows (perhaps in your package.json scripts section):
babel-watch -w src src/main.js
The difference is that instead of restarting whole babel-node process on every file change (which takes like 1.5sec on my MBP) it runs babel in parent process and starts "pure" node process with all transpiled JS files provided at your script startup.

Use nodemon:
Install it globally:
npm install -g nodemon
Use it on your project:
nodemon myscript.js
It will watch for changes in your project directory and restart the script when it sees them.

There are a lot of tools to do this. Take a look at this post:
Restart node upon changing a file
Maby the most common is Supervisor:
https://github.com/petruisfan/node-supervisor

The most popular tools for that purpose are nodemon, forever and supervisor. You can install them via npm. For other tasks like css pre-processors, minification, tests run etc. You can use task managers like Grunt or Gulp

use this supervisor -- -r 'babel-register' index.js because Error: Cannot find module 'babel/re‌​gister'. after checked the modules ,i thought it changed to babel-register and it works for me

Related

How to automate the build from the following configuration using gulp

Backdrop
I have a loopback and Angular app, Loopback gives use the server models and api's and using its sdk we are able to get client services.
Now i am planning to automate the following build process using gulp.
If any changes in the model is made then the sdk command is run and also the server is restarted/ and secondly when any changes to the angular files the sdk files are run and files are fetched from angular dist folder and server is restarted and best possible we can use live reload of browser.
Here is what i have tried and this never seems to work have been working on this for days.
Update
I was able to automate most of the stuff the one place where it fails is
gulp.task('browser-sync', function() {
browserSync.init(null, {
proxy: 'http://localhost:3000/home',
browser: 'google chrome',
port: 7000,
});
gulp.watch(['client/src/app/*.ts'], browserSync.reload);
let watcher = gulp.watch(['./common/models/**.js', './server/**.js', 'gulpfile.js'], ['sdk', 'server']);
watcher.on('change', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...'); // this watcher
});
});
gulp.task('sdk', function() {
spawn('./node_modules/.bin/lb-sdk', ['server/server.js', './client/src/app/shared/sdk', '-q'], {stdio: 'inherit'});
});
This watcher restarts the server and runs the sdk but it is failing in the sdk
The stack trace please help
via remoting. The Angular code for this scope won't be generated.
[19:29:37] Starting 'sdk'...
[19:29:37] Finished 'sdk' after 11 ms
[19:29:37] Starting 'server'...
[19:29:37] Finished 'server' after 17 ms
events.js:163
throw er; // Unhandled 'error' event
^
Error: spawn ./node_modules/.bin/lb-sdk ENOENT
at exports._errnoException (util.js:1050:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
at onErrorNT (internal/child_process.js:367:16)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
Update
I have multiple gulp task and one such is ng build -w which happens in a new directory for the same i change the process.chdir to change path and i also keep tab of this sdk so do i need to check the path again her . How can i check or give absolute paths in my spawn . if this is one of the probable causes of failure
Taking into account your update
What might be happening is that once you change your directory using process.chdir for a sepearate task and also you have kept watch on all the tasks . The path is set to the previous path and the gulp task is not able to find the sdk i:e spawn('./node_modules/.bin/lb-sdk', ['server/server.js', './client/src/app/shared/sdk', '-q'], {stdio: 'inherit'}); in that respective path .
To fix this you can add the following check in the sdk task
gulp.task('sdk', function() {
if (process.cwd() != __dirname) { // this checks for the current path
process.chdir(<change path>); // if it dosent match your base path change it here
}
spawn('./node_modules/.bin/lb-sdk', ['server/server.js', './client/src/app/shared/sdk', '-q'], {stdio: 'inherit'});
});
Are you sure you've run npm install --save-dev #mean-expert/loopback-sdk-builder?
Are you sure that gulpfile.js is in the same dir as package.json?
Are you certain ./node_modules/.bin/lb-sdk exists?
Have you tried reinstalling everything?
The answer to the error is simply that your spawn function can't find ./node_modules/.bin/lb-sdk. This is either because the file doesn't exist, or because the it can't be found relatively to your gulpfile.js
The ENOENT error in the console means "error: no entity". It comes from UNIX, rather than Node itself, and basically just translates to "file not found", but applies to a variety of generic things, not just files/directories.
Check that the file ./node_modules/.bin/lb-sdk definitely exists. Then check that your gulpfile is in the root relative to that directory.

The following gulp task is not working on windows but working on ubuntu

The gulp task
/* Run the npm script npm run buildLsdk using gulp */
gulp.task('sdk', function() {
if (process.cwd() != basePath) {
process.chdir('..');
// console.log(process.cwd());
}
spawn('./node_modules/.bin/lb-sdk', ['server/server.js', './client/src/app/shared/sdk', '-q'], {stdio: 'inherit'});
});
I am getting the following stack trace but i cannot debug
Error: spawn ./node_modules/.bin/lb-sdk ENOENT
at exports._errnoException (util.js:1022:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
at onErrorNT (internal/child_process.js:359:16)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
at Module.runMain (module.js:607:11)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
I have all the necessary files in node modules too any help is really appreciated.
More reference on the File use above - https://github.com/rahulrsingh09/loopback-Angular-Starter/blob/master/gulpfile.js
I think it's because lb-sdk.cmd is the file you're supposed to run on windows. when I changed the command to the below the error goes away. Please note the windows style directory slashes are different from linux.
gulp.task('sdk', function() {
spawn(
'.\\node_modules\\.bin\\lb-sdk.cmd',
[
'.\\server\\server.js',
'.\\client\\src\\app\\shared\\sdk',
'-q'
], {stdio: 'inherit'}
);
});
I found some more information,and I'm going to post a second answer I found (above one was accepted).
If you want to avoid changing directories in windows/linux you can use cross-spawn: https://www.npmjs.com/package/cross-spawn
win-spawn (from the chat dialog) is not maintained anymore per the github repo . If you're interested in using it make the following changes:
npm install cross-spawn
npm install spawn-sync
npm install strongloop (needs to be reinstalled per this link)
change 'google chrome' in browser-sync task to chrome.exe per this link:
run gulp
Please refer to this similar answer, this will solve your issue:
Convert the following npm script to gulp task
How to automate the build from the following configuration using gulp
And you can check the documentation of lb-sdk by typing ./node_modules/.bin/lb-sdk in your terminal.
Can you try using basePath when passing server/server.js and ./client/src/app/shared/sdk. Like for example:
spawn(
'./node_modules/.bin/lb-sdk',
[
basePath + '/server/server.js',
basePath + '/client/src/app/shared/sdk',
'-q'
], {stdio: 'inherit'}
);

Gulp-plumber not found in Ubuntu OS, but found in Windows OS on dual boot

I am following a tutorial, and I am supposed to have a gulpfile.js running, but I'm encountering a strange situation. Gulp works in one location and does not work in the other.
I have a dual boot for Ubuntu and Windows 8.1. In the Ubuntu OS Documents directory the gulp command does not work, but returns an error saying "'gulp-plumber' not found". I don't understand why since the folder structure is exactly the same. If I change directory to the windows volume and access the main project folder, when I type "gulp" everything works fine.
Additionally, if I CTRL-C in the command line, the gulp command stops working and returns an error saying:
events.js:163
throw er; // Unhandled 'error' event
Error: write EPIPE
So how can I run the gulp command again? Is it through ps aux, check something running and then kill it?
github.com/DannyS95/Project
This issue has been fixed, i had to install gulp plumber, because i did not have that package in the package.json file.
Then a quick npm install, and since i have gulp globally i can just run gulp and voila, it works.

sails debug command not working in Sails.js

I am creating my first sails.js app. When I tried
sails debug
I'm getting the following error on my command prompt
Debugger listening on port 5858
info: Starting app...
error: Grunt :: Error: listen EADDRINUSE
at exports._errnoException (util.js:746:11)
at Agent.Server._listen2 (net.js:1129:14)
at listen (net.js:1155:10)
at Agent.Server.listen (net.js:1240:5)
at Object.start (_debugger_agent.js:20:9)
at startup (node.js:86:9)
at node.js:814:3
To get the PID of the process using port:5858, I tried running
C:\Windows\system32>netstat -a -n -o
but unfortunately there is no process bound to port 5858. Am I missing something here?
I'm using Windows 8.1 with node.js v0.12.0 and sails.js 0.11.0
My server uses node 0.10.38 with sails because of some weird unfixed grunt thing with 11+. Haven't pulled up this issue in a while, but it looks like there's new activity... check out this comment in particular, which explains the issue and a possible fix (direct quote):
Possible Solution:
Looking at the options for child_process.fork, the --debug flag is being passed down to the child upon exiting the womb i.e. running
sails debug :
// ./node_modules/sails/bin/sails-debug.js
// Spin up child process for Sails
Womb.spawn('node', ['--debug', pathToSails, 'lift'], {
stdio: 'inherit'
});
setting options.execArgv to an empty array removes the flag and allows the process to continue:
// ./node_modules/sails/lib/hooks/grunt/index.js
var child = ChildProcess.fork(
path.join(__dirname, 'grunt-wrapper.js'),
[
taskName,
'--pathToSails='+pathToSails,
'--gdsrc='+ pathToSails + '/node_modules'
],
{
silent: true,
stdio: 'pipe',
execArgv: []
}
);
It seems like a bug in Sails. You can apply the fix your self by replacing your Sails' file:
./node_modules/sails/lib/hooks/grunt/index.js
with the contents of the following:
https://raw.githubusercontent.com/balderdashy/sails/88ffc0ed9949f8c74ea390efb5610b0e378fa02c/lib/hooks/grunt/index.js
This is the file that will be in the Sails' release v12.
Did you try to run in debug like simple node.js?
node --debug app.js

Error message from "jspm install jquery"

I am working through the tutorial on the jspm.io site
https://github.com/jspm/jspm-cli/wiki/Getting-Started
All works fine until I get to item 3, where I try to execute
jspm install jquery
and I get this error message
warn Error on getOverride for jspm:github, retrying (2).
ReferenceError: ui is not defined
at c:\Projects\Project1\node_modules\jspm\node_modules\jspm-registry\registry.js:157:5
nodejs is v0.12.0
npm is 2.5.1
jspm is 0.14.0
and this is on Windows 8.1
Does anyone have any clue what is causing this?
This looks like it was because there was an error while jspm was trying to create the local registry clone. Ensure you have git installed as git on your machine. Otherwise it may be a permissions issue.
This was a logging bug though - have fixed it with an update to the registry, so that the error should be slightly more useful next time if you update jspm.
I was getting a similar error with jspm but my problem was actually in how nodejs child_process.exec was calling the git command.
child_process.exec was running
C:\Windows\system32\cmd.exe /s /c "git clone --depth=1 github.com/jspm/registry.git .
However cmd.exe was still auto running commands set in the registry first. In my case the command changing the working folder. So the cwd was being overridden.
Check your registry settings for:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
If there is a command in there to set the drive of working folder it will cause the above error.
Also
With your working folder as c:\, try ruuning the following nodejs code:
var exec = require('child_process').exec;
exec('dir', { cwd: 'C:/windows/fonts' }, function(error, stdout, stderr) {
console.log('stdout: ' + stdout);
});
If it does not list the contents of the fonts folder then your problem is more likely with child_process.exec in node

Categories