Using LowDB on Electron APP - angularjs

I'm developing a basic app made with Electron and AngularJS. For this purpose I'm using the electron boilerplate (https://github.com/szwacz/electron-boilerplate) and for database, I'm using LowDB(https://github.com/typicode/lowdb).
I have been able to create a database(JSON) and read it from a script. But my problem is when I want to update and save. I can update, and the change is reflected on the JSON file, but when I start the app again, the JSON has the same data that at the beginning (it is overwritten).
I think it is a problem with the build task of Electron boilerplate, that always overwrites the file. I thought that when I did the task to release the app, it will fixes(npm run release), but not, it overwrites the json.
I am loading the database so:
import low from 'lowdb';
import storage from 'lowdb/file-sync';
import {
remote
}
from 'electron';
var fs = require('fs');
var app = remote.require('app');
const db = low(__dirname + '/db.json', {
storage
});
document.addEventListener('DOMContentLoaded', function() {
db('users').push({
'name': 'foo'
});
});
This script is loaded at the beginning, so it should add, every time that app is started, a new entry. The script is writting the new entry in JSON file but when the start is restarted, the JSON back to the previous state.
At the end, I am using the localStorage, but I would like to use LowDB to save the data locally.
Here is the task (gulp file) that I commented before about the build of app:
'use strict';
var pathUtil = require('path');
var Q = require('q');
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
var plumber = require('gulp-plumber');
var jetpack = require('fs-jetpack');
var bundle = require('./bundle');
var generateSpecImportsFile = require('./generate_spec_imports');
var utils = require('../utils');
var projectDir = jetpack;
var srcDir = projectDir.cwd('./app');
var destDir = projectDir.cwd('./build');
var paths = {
copyFromAppDir: [
'./node_modules/**',
'./bower_components/**',
'./components/**',
'./scripts/**',
'./shared.services/**',
'./sections/**',
'./helpers/**',
'./db.json',
'./**/*.html',
'./**/*.+(jpg|png|svg|eot|ttf|woff|woff2)'
],
}
// -------------------------------------
// Tasks
// -------------------------------------
gulp.task('sass', ['clean'], function() {
console.log('Compiling SASS...');
gulp.src('app/styles/scss/main.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(destDir.path('styles')));
});
gulp.task('watch:sass', function() {
console.log('Watching SASS...');
var sassWatcher = gulp.watch(['app/styles/scss/*.scss','app/**/**/*.scss'], ['sass']);
sassWatcher.on('change', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});
gulp.src('app/styles/scss/main.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(destDir.path('styles')));
});
gulp.task('clean', function (callback) {
return destDir.dirAsync('.', { empty: true });
});
var copyTask = function () {
return projectDir.copyAsync('app', destDir.path(), {
overwrite: true,
matching: paths.copyFromAppDir
});
};
gulp.task('copy', ['clean'], copyTask);
gulp.task('copy-watch', copyTask);
var bundleApplication = function () {
return Q.all([
bundle(srcDir.path('background.js'), destDir.path('background.js')),
bundle(srcDir.path('app.js'), destDir.path('app.js')),
bundle(srcDir.path('script.js'), destDir.path('script.js')),
]);
};
var bundleSpecs = function () {
return generateSpecImportsFile().then(function (specEntryPointPath) {
return bundle(specEntryPointPath, destDir.path('spec.js'));
});
};
var bundleTask = function () {
if (utils.getEnvName() === 'test') {
return bundleSpecs();
}
return bundleApplication();
};
gulp.task('bundle', ['clean'], bundleTask);
gulp.task('bundle-watch', bundleTask);
gulp.task('finalize', ['clean'], function () {
var manifest = srcDir.read('package.json', 'json');
// Add "dev" or "test" suffix to name, so Electron will write all data
// like cookies and localStorage in separate places for each environment.
switch (utils.getEnvName()) {
case 'development':
manifest.name += '-dev';
manifest.productName += ' Dev';
break;
case 'test':
manifest.name += '-test';
manifest.productName += ' Test';
break;
}
// Copy environment variables to package.json file for easy use
// in the running application. This is not official way of doing
// things, but also isn't prohibited ;)
manifest.env = projectDir.read('config/env_' + utils.getEnvName() + '.json', 'json');
destDir.write('package.json', manifest);
});
gulp.task('watch', function () {
watch('app/**/*.js', batch(function (events, done) {
gulp.start('bundle-watch', done);
}));
watch(paths.copyFromAppDir, { cwd: 'app' }, batch(function (events, done) {
gulp.start('copy-watch', done);
}));
watch('app/**/scss/*.scss', batch(function (events, done) {
gulp.start('watch:sass', done);
}));
watch('app/**/**/*.scss', batch(function (events, done) {
gulp.start('watch:sass');
}));
});
gulp.task('build', ['bundle', 'sass', 'copy', 'finalize']);
How you can see, in 'copyFromAppDir' there is a db.json. This file is my database, but I want update it and changes persist, but I am not be able to do that.
Kind regards!

It looks like your gulp task 'clean' is overwriting your db.json file. Because you are using lowDB, this is the same as overwriting your database. If you remove the line './db.json', from the 'copyFromAppDir' array the changes should persist.
Like this:
var paths = {
copyFromAppDir: [
'./node_modules/**',
'./bower_components/**',
'./components/**',
'./scripts/**',
'./shared.services/**',
'./sections/**',
'./helpers/**',
'./**/*.html',
'./**/*.+(jpg|png|svg|eot|ttf|woff|woff2)'
],
}

Related

GULP: rename the affected file only

I want to create a copy with a new extension in the same folder only of the file which was changed. How should src and dest be specified?
var gulp = require('gulp'),
rename = require("gulp-rename"),
watch = require('gulp-watch');
var filePath = "./repo/**/*.xml"
gulp.task('watch', function () {
watch(filePath, gulp.series('rename'));
});
gulp.task('rename', function () {
return gulp.src(???).pipe(rename(function (path) {
path.extname = ".mei";
})).pipe(gulp.dest(???));
});
Try this:
var gulp = require('gulp'),
rename = require("gulp-rename"),
watch = require('gulp-watch'),
changedInPlace = require('gulp-changed-in-place');
var filePath = "./repo/**/*.xml"
gulp.task('watch', function () {
watch(filePath, gulp.series('rename'));
});
gulp.task('rename', function () {
return gulp.src(filePath)
.pipe(changedInPlace())
.pipe(rename(function (path) {
console.log(path);
path.extname = ".mei";
}))
.pipe(gulp.dest('repo'));
});
gulp.task('default', gulp.series('rename', 'watch'));
This uses the gulp-changed-in-place plugin to only pass through files that have changed in the same directory (in your case filePath).
It does have a firstRun option but I couldn't get it to work properly - maybe that option doesn't play well with gulp v4? To work around that, rename is called once before the watch is set up, see
gulp.task('default', gulp.series('rename', 'watch'));
Now it will only change the extension of the changed file and add that changed file back into the same directory it started in.

Refreshing a browser's cache while developing with gulp

My project's setup uses a combination of python's Flask on the backend which serves a fairly simple javascript React webpage using gulp.
Whether I'm debugging frontend code through Chrome or Firefox, I have to do a hard refresh multiple times before the changes make it to the browser. I see the gulp console log Finished 'transform' after N ms after each save, which leads me to believe it's the browsers fault.
I am not a front end engineer so I'm wondering what more experienced devs use. Hitting Cmd+Shift+R 5-20 times after each save is a little mind bogglingly inefficient.
current gulpfile.js:
'use strict';
var gulp = require('gulp'),
browserify = require('browserify'),
size = require('gulp-size'),
del = require('del'),
babelify = require('babelify'),
source = require('vinyl-source-stream'),
gutil = require('gulp-util');
var compiled_dir = './static/scripts/jsc';
var js_dir = './static/scripts/js';
function handle_error(err) {
gutil.log(err.message);
gutil.beep();
return process.exit(2);
}
gulp.task('transform', function () {
browserify({ entries: js_dir + '/main.js', debug: true })
.transform(babelify)
.bundle()
.on('error', handle_error)
.pipe(source('main.js'))
.pipe(gulp.dest(compiled_dir));
browserify({ entries: js_dir + '/userMgmt.js', debug: true })
.transform(babelify)
.bundle()
.on('error', handle_error)
.pipe(source('userMgmt.js'))
.pipe(gulp.dest(compiled_dir));
});
gulp.task('clean', function (cb) {
del([compiled_dir], cb);
});
gulp.task('default', ['clean'], function () {
gulp.start('transform');
gulp.watch(js_dir + "/*", ['transform']);
});
Method 1: Use this gulp-cache package to disable cache in development mode.
This will work:
var gulp = require('gulp');
var usemin = require('gulp-usemin');
var cache = require('gulp-cache');
gulp.task('default', function () {
return gulp.src('src/index.html')
.pipe(gulp.task('clear', function (done) {
return cache.clearAll(done);
});)
.pipe(usemin({
js: []
}))
.pipe(gulp.dest('dist'));
});
If you don't know how to use it, please update your question with gulp config file, I will configure you that.
Method 2: Configure your watcher.
$ npm install browser-sync --save-dev
var browserSync = require('browser-sync').create();
gulp.watch(['./**/*.{scss,css,html,py,js}'], ['clearCache', browserSync.reload]);
gulp.task('clearCache', function (done) {
return cache.clearAll(done);
});

How can I start the angular app with this gulp script?

I took a gulpfile from this location https://github.com/meanjs/mean. My version looks like this, I used a slightly moderated version just to run a dev version:
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
fs = require('fs'),
defaultAssets = require('./config/default'),
glob = require('glob'),
gulp = require('gulp'),
gulpLoadPlugins = require('gulp-load-plugins'),
runSequence = require('run-sequence'),
plugins = gulpLoadPlugins({
rename: {
'gulp-angular-templatecache': 'templateCache'
}
}),
path = require('path'),
endOfLine = require('os').EOL;
// Local settings
var changedTestFiles = [];
// Set NODE_ENV to 'development'
gulp.task('env:dev', function () {
process.env.NODE_ENV = 'development';
});
// Nodemon task
gulp.task('nodemon', function () {
return plugins.nodemon({
script: 'server.js',
nodeArgs: ['--debug'],
ext: 'js,html',
watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
});
});
// Watch Files For Changes
gulp.task('watch', function () {
// Start livereload
plugins.livereload.listen();
// Add watch rules
gulp.watch(defaultAssets.server.views).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.server.allJS, ['eslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.client.js, ['eslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.livereload.changed);
gulp.watch(defaultAssets.server.gulpConfig, ['eslint']);
gulp.watch(defaultAssets.client.views).on('change', plugins.livereload.changed);
// }
});
// Run the project in development mode
gulp.task('default', function (done) {
runSequence('env:dev', ['watch', 'nodemon'], done);
});
I got the server working fine but there is nothing showing up on localhost:3000? How can i fix this?

How To Get Constant Inside ui-router (Angular) state function

I want to reference a "constant" that is defined outside this state function but if I try to pass it in as a provider it errors because constants are not providers. That is, I want to do something like:
var exports = module.exports = function ($stateProvider,configData) { ...
But that fails. How can I get my javascript variable baseDirectory passed in.
The bigger problem is that the webroot is not always at the same url. sometimes it is /ng and sometimes it is just / and I want to be able to set that as a config someplace I can load into a config file (not hard code into the state function.
var exports = module.exports = function ($stateProvider) {
$stateProvider.state('home', {
url: baseDirectory + '/home',
templateUrl: '/templates/home/home.html',
controller: 'HomeController',
});
};
exports.$inject = ['$stateProvider'];
I got the same issue, what I did, is to build a constant in the app, and replace them with new value in gulp task when the base url changed.
It had many apps, so my idea is dumb and simple, just find and replace the value of the content in the app by the new value input from gulp task configuration.
It's not smart, but works.
In the example, I have three apps in /clinic, /panel, /company, and for each of them, it had a build.js in it.
The build.js will build the app, and replace the constant value.
I have many apps, so I do this:
var gulp = require('gulp');
var concat = require('gulp-concat');
var taskBuildClinic = require("./clinic/build");
var taskBuildPanel = require("./panel/build");
var taskBuildCompany = require("./company/build");
var migrate = require("./laravel/migrate");
var env = {
'dev': {
EndpointBaseUrl: "'/admin/public/';",
TemplateBaseUrl: "'/admin/public';"
}
};
// ./node_modules/.bin/gulp
gulp.task('clinic', function (cb) {
return taskBuildClinic(gulp, env);
});
gulp.task('company', function (cb) {
return taskBuildCompany(gulp, env);
});
gulp.task('panel', function (cb) {
return taskBuildPanel(gulp, env);
});
In each build.js located in different app, it had:
var concat = require('gulp-concat');
var replace = require('gulp-replace');
...
if (env['production']) {
// replace something not for production
endpoint = "var EndpointBaseUrl = " + env['production']['EndpointBaseUrl'];
templateBaseUrl = "var TemplateBaseUrl = " + env['production']['TemplateBaseUrl'];
console.log(endpoint);
console.log(templateBaseUrl);
} else {
endpoint = "var EndpointBaseUrl = " + env['dev']['EndpointBaseUrl'];
templateBaseUrl = "var TemplateBaseUrl = " + env['dev']['TemplateBaseUrl'];
console.log(endpoint);
}
return gulp.src(files)
.pipe(concat(prefix + '.js'))
.pipe(replace(/var EndpointBaseUrl.*?;/g, endpoint))
.pipe(replace(/var TemplateBaseUrl.*?;/g, templateBaseUrl))
.pipe(gulp.dest('./build'));
In the app, I had:
var TemplateBaseUrl = "";
var EndpointBaseUrl = "";
Their content will be replaced by the value from gulp task.

Protractor/Jasmine do not create folder for xunit file when it does not exist

I have a protractor instance that tests my app.
The following is my config for where the jasmine.JUnitXmlReporter should write the results file.
onPrepare: function () {
require('jasmine-reporters');
var capsPromise = browser.getCapabilities();
capsPromise.then(function (caps) {
var browserName = caps.caps_.browserName.toUpperCase();
var browserVersion = caps.caps_.version;
var prePendStr = browserName + '-' + browserVersion + '-';
jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter('test-results/protractor/', true, true, prePendStr));
});
},...
This presents a bit of an interesting challenge for git, because it won't track a folder unless there is a file in it. Which means that when my CI server is working on this, the file won't get written unless I put some other dummy file there.
I've played with the permissions on the folders, and that doesn't help. Is there something I'm doing wrong here? Running karma unit tests doesn't exhibit this same problem, e.g.:
junitReporter: {
outputFile: 'test-results/unit/results.xml',
suite: ''
},
This is how JUnitXmlReporter is made. You can see it's source code here.
You can use File System module here to make the folder needed before setting up the JUnitXmlReporter
var fs = require('fs')
fs.mkdirSync('unit');
fs.mkdirSync('unit/test-results');
jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter('test-results/protractor/'..
There is also a mkdirp module in NPM for avoiding errors when folder already is there.
My solution ended up being a combination of what #Mohsen suggest above and this SO question.
Instead of using synchronous file processing I opted to use Q to turn the mkdir calls into promises. Additionally, the capsPromise appends the browser version to the output file for extra information.
onPrepare: function () {
require('jasmine-reporters');
var fs = require('fs');
var Q = require('q');
var mkdir = Q.denodeify(fs.mkdir);
mkdir('test/test-results')
.then(function(data) {
mkdir('test/test-results/protractor')
.then(function(data) {
var capsPromise = browser.getCapabilities();
capsPromise.then(function (caps) {
var browserName = caps.caps_.browserName.toUpperCase();
var browserVersion = caps.caps_.version;
var prePendStr = browserName + '-' + browserVersion + '-';
jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter('test/test-results/protractor/', true, true, prePendStr));
});
})
.fail(function(err) {
console.err('Error creating directory ' + err);
})
})
.fail(function(err) {
console.err('Error creating directory ' + err);
});
},

Resources