suggestion on workflow and tools to work with node.js - node.js

I'm developing some really simple node.js libraries for learning purposes.
It's about functions like HexToBase64 and things like that.
Ideally, I'd like to program in a text editor, and play with it on the node repl, having the code automatically reloaded on the repl on every save.
Any module or tool to interactively play with node?

There are modules such as supervisor, nodemon and forever that can reload your application on a code change. Otherwise, you can create your own implementation like this:
var fs = require('fs');
var cluster = require('cluster');
if (cluster.isMaster) {
var worker = cluster.fork();
fs.watch(process.argv[1], function(event, filename) {
worker.kill();
worker = cluster.fork();
});
}
if (cluster.isWorker) {
// put your application logic here that will
// run when this file changes
}
As for using Node interactively, you can just run node in a terminal and you have an interactive console. If you needed to load a script and use it interactively, then you would use .load script.js.

Related

Set up a server from within an electron app

I haven't had any success looking for this because I mostly find misleading questions, about people wanting to use data from a server inside of their electron app. That's not my case.
I have a regular app, which uses a server on the internet, just like any other, but we want to make it available for schools without internet (without any or without reliable internet), so what I'm trying to do is to create a version of my server which runs from an electron exe and serves files for the students conected to the wifi (but no the internet) to access. After the process is done "offline", I will sync the data from the electron app itself.
I tried to run a server from express but I didn't have any progress so far. What I tried was to put the exact same code from my node server in my main.js file and had no luck.
I know that's not what electron is supposed to do, if you're positively sure there is no way to do that, please tell me so I can search for another alternative.
A simple approach is to create a cluster where the master process is the Electron Main and the worker process is the server.
Example:
Change the main on package.json to start.js
On start.js write:
const cluster = require('cluster');
if (cluster.isMaster) {
require('./main.js'); // your electron main file
cluster.fork();
} else {
require('./server.js'); // your server code
}

write polling service in node.js with sails.js framework

i have project in sails.js, i want to write a polling service that check some record in some interval and after that send email. my example code is:
module.exports.bootstrap = function(cb) {
cb();
var refresh = function() {
setTimeout(doWork, //someInterval);
};
var doWork = function() {
if (//check some condition) {
sendEmail();
}
refresh();
};
doWork();
}
i use pm2 libary and start my project with cluster mode. example code is:
pm2 start app.js -i 4
this command run app.js in cluster mode with 4 process.
the problem is my polling service run in all process because i run my polling service in config/bootstrap.js file and this is very bad.
my question is how can i run my service once in all process?
You can check if process is master and then run script only on that case.
var cluster = require('cluster');
if(cluster.isMaster) // rest of your service...
But for me... This is strange logic... You should queue your tasks to shared db, and when task is pooled remove it from it etc.

How to wait for a Redis connection?

I'm currently trying to use Node.js Kue for processing jobs in a queue, but I believe I'm not doing it right.
Indeed the way I'm working now, I have two different services (which in this case I'm running with Docker Compose): one Web API built with Express with sends jobs to the queue and one processing module. The issue here is with the processing module.
I've coded it as follows:
var kue = require('kue');
var config = require('./config');
var queue = kue.createQueue({
prefix: config.redis.queuePrefix,
redis: {
port: config.redis.port,
host: config.redis.host
}
});
queue.process('jobType', function (job, done) {
// do processing here...
});
When we run this with Node, it sits there waiting for things to be placed on the queue to do the processing.
There are two issues however:
It needs that Redis be available before running this module. If we run this without Redis already available, it crashes because the host is not accessible and ends the process.
If Redis suddenly becomes unavailable, the processing module also crashes because it cannot stablish the connection and the process is killed.
How can I avoid these problems?
My guess is that I should somehow make the code "wait" for Redis, but I have no idea on how to do this.
How can this be done in this case?
You can use promise to wait until redis is loaded. Then run your module.
loadRedis().then(() => {
//load your module
})
Or you can use generator to "stop" until redis is loaded.
function*(){
const redisLoaded = yield loadRedis();
//load your module
}

Execute createShortcut in a Squirrel event, in an Electron app

I'm trying to create shortcuts for my Electron app when I install it or update it, however I am having some trouble executing the command that is meant to create the shortcut.
By default Electron apps are "SquirrelAware", therefore I have to specify where i would like to create shortcuts.
My question is in relation to the accepted answer to this question.
Handle Squirrel's event on an Electron app
I have tried to use the exec module and the child_process module, however both did not seem to work. I am now currently attempting (and failing) to launch PowerShell and run a script in there that will create shortcuts on my Start Menu and Desktop, however I feel this is rather long and that there must be an easier way.
Here is my current attempt using the child_process module and PowerShell:
var spawn = require('child_process').spawn, child;
child = spawn("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",["C:\\ElectronSquirrelDemo\\AddAppShortcuts.ps1 -SourceExe "+ executionPath] );
child.stdout.on('data', function(data){
console.log("PowerShell Data: " + data);
});
child.stdout.on('data', function(data){
console.log("PowerShell Error: " + data);
});
child.stdout.on('exit', function(){
console.log('PowerShell script finished');
});
Any help on this would be much appreciated
It took me awhile to understand how to do this myself. The Squirrel.Windows Update.exe has the ability to create shortcuts to your app for you. I wrote a blog post called Creating a Windows Distribution of an Electron App using Squirrel and in it I have Squirrel create the shortcuts for me. If you want to go this route, this is simplified version of how to have Squirrel create the shortcuts for you:
var cp = require('child_process');
var updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
var target = path.basename(process.execPath);
var child = cp.spawn(updateDotExe, ["--createShortcut", target], { detached: true });
child.on('close', function(code) {
app.quit();
});
You need to hack the electron executable using Resource Hacker, rcedit, or another application to change the ProductName and Icon resources. You'll want to call the above code on both the install and updated Squirrel events.

How to get grunt.js to start an express app for testing

My current situation is that I use grunt to make a production version of my express app (minimize and merge all the js/css, copy all the files in place) and then I have to run a script which sets an environment variables (my app only serves the test harness when running in TEST mode), creates an empty Mongo test database and then calls npm start on the application directory, and then I manually have to run the tests from either Chrome or Phantom, what I want to do is have grunt set the environment variable and run the server, run the tests, and then stop the server (in the future if all is successful it would be nice to have it deploy as well). However when I try to run the app in grunt, it gets stopped as soon as it is completed.
How do I have grunt start the app, wait until it is started and then run tests?
If you check grunt-express which is a plugin for express web-server tasks via grunt.
express-keepalive
Note that this server only runs as long as grunt is running. Once
grunt's tasks have completed, the web server stops. This behavior can
be changed by appending a express-keepalive task at the end of your
task list like so
grunt.registerTask('myServer', ['express', 'express-keepalive']);
Now when you run grunt myServer, your express server will be kept alive
until you manually terminate it.
Such feature can also be enabled ad-hoc by running the task like grunt express express-keepalive.
This design gives you the flexibility to use grunt-express in
conjunction with another task that is run immediately afterwards, like
the grunt-contrib-qunit plugin qunit task. If we force express task to
be always async, such use case can no longer happen.
From the guide grunt-contrib-qunit package is used to run QUnit unit tests in a headless PhantomJS instance. Also mind the last line, if you force express to be always async it would be of no use.
npm link for grunt-express.
I'm not sure if I understand your problem correctly, but probably this helps:
Do you know about Grunt's async function? For some time I used the following approach to start (and stop) my Express app. I used it with watch, so it automatically restarted on save. In this case you have to set watch's nospawn option to true.
var server = null;
grunt.registerTask('server', 'Start server', function() {
var done = this.async();
if (server !== null) {
server.close();
clearCache();
}
var app = require('./my-express-app.js');
server = http.createServer(app).listen(app.get('port'), function(){
done();
});
});
function clearCache() {
for (key in require.cache) {
if (key.indexOf(__dirname + '/node_modules/') == -1) {
delete require.cache[key];
}
}
}
It is ugly because of this require-cache-hack. However, it works.

Resources