I write a tool for migrating data using Bluebird promise, so that user can trigger this tool directly via node command. Example:
node migrate.js
The problem is, this node process will not exist after complete. Here is the content of main migrate.js, the exec() function return a promise.
var migrate = require('../elasticsearch/migrate');
var setting = require('../../config/setting');
var cmd = new migrate(setting.NewConfig.search, true);
cmd.exec()
.then(function () {
console.info('Operation completed');
})
.catch(function (err) {
console.error(err);
});
At the moment, I force it exit by invoke process.exit(0);
The content of migrate.js, some code I can't expose so I remove them out
'use strict';
var Promise = require('bluebird');
var request = Promise.promisifyAll(require('request'));
var _ = require('lodash');
var index = require('./mapping.json');
var Schema = require('../../app/database/mysql/model');
var common = require('../../utils/common');
var client = require('../../utils/search');
var logger = require('../../utils/logger');
function Migrate(opts, enable) {
this.buildInLogger = enable == undefined;
this.opts = opts || {};
// Sensitive code
// ....
this.options = {
url: this.opts.protocol + '://' + this.opts.host + '/' + this.opts.index,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
}
Migrate.prototype.initElasticsearch = function () {
var self = this;
var options = _.clone(this.options);
return request.delAsync(options)
.then(function () {
options = _.clone(self.options);
options.json = index;
return request.putAsync(options);
})
.then(function () {
if (self.buildInLogger) {
logger.info('Init new index successfully');
}
else {
console.log('Init new index successfully');
}
})
.catch(function (err) {
if (self.buildInLogger) {
logger.error(err);
}
else {
console.error(err);
}
});
};
Migrate.prototype.exec = function () {
var self = this;
return this.initElasticsearch()
.then(function(){
// Sensitive code which also return a promise
// ....
})
.catch(function (err) {
if (self.buildInLogger) {
logger.error(err);
}
else {
console.error(err);
}
})
};
module.exports = Migrate;