So I am working with Flutter but each time I Hot Restart the app it overwrites my data.json.
// reference one of the data.json
regulatorAsync(licenseText) async {
Directory dir = await getApplicationDocumentsDirectory();
File file = File('${dir.path}/data1.json');
if (!await file.exists()) {
print("File doesn't exist");
// if it doesn't exist, create it
file = await file.create();
file = await file.writeAsString(await file.readAsString());
}
if (await file.readAsString() == "") {
print("File is empty");
file = await file.writeAsString('{"newuser": true}');
}
var json = jsonDecode(await file.readAsString());
print(json);
var a = regulator(json, licenseText);
return a;
}
//reference 2
onPressed: () async {
// write data to file
var data = await rootBundle.loadString('lib/mainapp/data.json');
var js = jsonDecode(data);
js["newuser"] = false;
var js2 = jsonEncode(js);
// get the path to the document directory.
Directory tempDir = await getTemporaryDirectory();
var appDocPath = tempDir.path;
print(js2);
var file = await File('$appDocPath/data1.json').writeAsString(js2);
print(file.readAsStringSync());
Navigator.of(context).pushReplacementNamed('/AllowPerms');
},
I know for sure there are no other refrences I even changed the names of the files to data1.json. I get back {"newusers": true} while with the onPress it should have been set to false.
Related
My webpage provides functionallity to convert pdf to image.
For Webpage i am using Firebase Hosting and for functions obvs Functions.
But after file upload function logs error in firebase dashboard Boundary not found
Below is the code i used to upload file in html:
function uploadFile() {
var file = document.getElementById("file_input").files[0];
var pass = document.getElementById("pass").value;
console.log(file + pass);
var formdata = new FormData();
formdata.append("file", file);
formdata.append("password", pass);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "/upload");
ajax.setRequestHeader("Content-Type", "multipart/form-data");
ajax.send(formdata);
}
and this is the code of functions:
var functions = require('firebase-functions');
var process;
var Busboy;
var path = require('path');
var os = require('os');
var fs = require('fs');
exports.upload = functions.https.onRequest((req, res) => {
const busboy = new Busboy({ headers: req.headers });
const fields = {};
const tmpdir = os.tmpdir();
const uploads = {};
const fileWrites = [];
var pass = '';
busboy.on('file', (fieldname, file, filename) => {
console.log(`Processed file ${filename}`);
const filepath = path.join(tmpdir, filename);
uploads[fieldname] = filepath;
const writeStream = fs.createWriteStream(filepath);
file.pipe(writeStream);
const promise = new Promise((resolve, reject) => {
file.on('end', () => {
writeStream.end();
});
writeStream.on('finish', resolve);
writeStream.on('error', reject);
});
fileWrites.push(promise);
});
busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
pass = val;
});
busboy.on('finish', function () {
console.log('Done parsing form!');
console.log(pass);
console.log(uploads);
process.processCard(uploads['file'], pass, 2).then((s) => {
res.end(`
<!DOCTYPE html>
<html>
<body>
ImageConverted!!
<img src="data:image/jpeg;base64,${s}" width="90%"></img>
</body>
</html>
`);
}).catch((err) => { res.end('Error: ' + err) });
});
busboy.end(req.body);
});
What am i doing wrong ?
For multipart body it is recommended to use req.rawBody instead of req.body
https://stackoverflow.com/a/48289899/6003934
I've got a small postcss plugin I've made that generates a JSON file off a colors.css variable file during webpack build.
My postcss plugin
const fs = require('fs');
const postcss = require('postcss');
const capitalize = (string) => string.charAt(0).toUpperCase() + string.slice(1);
const getPropName = (string) => {
let name = clean(string.split('-'));
name.shift();
for(let k = 1; k < name.length; k++){ //start at 1 to skip 'color' prefix
name[k] = capitalize(name[k].toString());
}
return name.join('');
};
const clean = (array) => {
let i = array.length;
while(i--){
if (!array[i]) {
array.splice(i, 1);
i++;
}
}
return array;
};
module.exports = postcss.plugin('cssobject', (files, filters, options) =>
(css) => {
options = options || {
destination: ''
};
// Processing code will be added here
const getVariable = (variable) => {
let result;
css.walkRules((rules) => {
rules.walkDecls((decl) => {
const pointer = variable.replace('var(', '').replace(')','');
if(!decl.prop.match(pointer)) return;
result = decl.value;
});
});
return result;
};
css.walkRules((rules) => { //hooks into CSS stream
let i = files.length;
let cssObject = {};
while (i--) {
if(!rules.source.input.from.match(files[i])) return; //scrubs against requested files
rules.walkDecls((decl) => {
let j = filters.length;
while(j--){
if(!decl.prop.match(filters[j])) return; //scrubs against requested rules
let prop = getPropName(decl.prop);
cssObject[prop] = (decl.value.match('var'))? getVariable(decl.value) : decl.value;
}
});
}
if (options.destination) {
fs.writeFile(options.destination, JSON.stringify(cssObject), 'utf8');
}
});
}
);
I'm then importing this JSON file into a react component JSX file to then parse JSON data into a visual guide of project's used colors under AA and AAA requirements... anywho
The problem I'm having is my webpack-dev-server keeps re-building over and over again cause it thinks a change has been made to the JSX file, when in fact it's only ever a change to the JSON file being imported.
Is there a standard way of importing generated files in to a JSX without causing infinite build loops?
I've already tried having the JSON file be saved well outside of the webpack dev's watch location, and still build loop remains.
Thanks in advance!
you can change you file's timestamp, the webpack will not build after you change your file
const now = Date.now() / 1000;
const lastModifyTime = now - 11;
const lastAccessTime = now - 11;
fs.utimesSync(jsonPath, lastModifyTime, lastAccessTime);
Have a try, hope to help you.
I have one interesting question. Is it possible to change some file inside open stream (EventStream) inside gulp?
I have that stuff. I want to read some file inside opened stream and write that stuff to other file. How I can do it? Thanks.
gulp.task('handleGlobalStorage', function () {
return gulp.src('./global_storage.js')
.pipe(setEnvHostAndProxy())
.pipe(gulp.dest('./built'));
});
function setEnvHostAndProxy() {
return es.map(function(file, cb) {
var fileContent = file.contents.toString();
//some changes inside content
// if (!gutil.env.dev) return;
/* I have stuff that fetched from file and I modify it that I send it
down to pipe. But also I want to insert this stuff inside other
file. How I can do it? Should I create WritableStream of that file
and merge it ?*/
file.contents = new Buffer(fileContent);
// send the updated file down the pipe
cb(null, file);
});
}
I resolved that issue, here is solution (I will not show all code, only general). The main concept is - open file and write new stuff inside pipe :) that's all.
function setEnvHostAndProxy() {
var bsConfigFileContent = fs.readFileSync('./bs-config.js', 'utf8'),
bsConfigProxyPattern = /(proxyUrl\s?=\s?)["|'](.*)["|']/;
return es.map(function (file, cb) {
var fileContent = file.contents.toString(),
prodHost = fileContent.match(generateRegExpForHosts('prodHost'))[1],
prodProxy = fileContent.match(generateRegExpForHosts('prodProxy'))[1],
devProxy = fileContent.match(generateRegExpForHosts('devProxy'))[1],
devHost = fileContent.match(generateRegExpForHosts('devHost'))[1],
changedBsConfigFileStream,
res;
if (!gutil.env.dev) {
res = prodHandler();
changedBsConfigFileStream = bsConfigHandler(prodHost);
} else {
res = devHandler();
changedBsConfigFileStream = bsConfigHandler(devProxy);
}
fs.writeFile('./bs-config.js', changedBsConfigFileStream, 'utf8', function (err) {
if (err) throw (err);
});
file.contents = new Buffer(res);
cb(null, file);
} });
I have a folder of HTML files that contain a comment at the top with metadata. I would like to run one gulp-replace operation if the metadata matches one regex, and another gulp-replace operation if it doesn't match, then continue on with the rest of the tasks pipeline. If tried various iterations using gulp-if but it always results in "TypeError: undefined is not a function" errors
import gulp from 'gulp';
import plugins from 'gulp-load-plugins';
const $ = plugins();
function preprocess() {
var template_data = new RegExp('<!-- template_language:(\\w+)? -->\n', 'i');
var handlebars = new RegExp('<!-- template_language:handlebars -->', 'i');
var primaryColor = new RegExp('#dc002d', 'gi');
var mailchimpColorTag = '*|PRIMARY_COLOR|*';
var handlebarsColorTag = '{{PRIMARY_COLOR}}';
var replaceCondition = function (file) {
return file.contents.toString().match(handlebars);
}
return gulp.src('dist/**/*.html')
.pipe($.if(
replaceCondition,
$.replace(primaryColor, handlebarsColorTag),
$.replace(primaryColor, mailchimpColorTag)
))
.pipe($.replace, template_data, '')
.pipe(gulp.dest('dist'));
}
What's the most efficient way to go about this?
gulp-filter was the answer. Whereas gulp-if can be used to decide whether a particular operation should be applied to the whole stream, gulp-filter can be used to decide which files in a stream an operation should be applied to.
import gulp from 'gulp';
import plugins from 'gulp-load-plugins';
const $ = plugins();
function preprocess() {
var template_language = new RegExp('<!-- template_language:(\\w+)? -->\n', 'i');
var handlebars = 'handlebars';
var primaryColor = new RegExp('#dc002d', 'gi');
var handlebarsColorTag = '{{PRIMARY_COLOR}}';
var handlebarsCondition = function (file) {
var match = file.contents.toString().match(template_language);
return (match && match[1] == handlebars);
}
var handlebarsFilter = $.filter(handlebarsCondition, {restore: true});
var mailchimpColorTag = '*|PRIMARY_COLOR|*';
var mailchimpCondition = function (file) {
return !handlebarsCondition(file);
}
var mailchimpFilter = $.filter(mailchimpCondition, {restore: true});
return gulp.src('dist/**/*.html')
.pipe(handlebarsFilter)
.pipe($.replace(primaryColor, handlebarsColorTag))
.pipe($.debug({title: 'Applying ' + handlebarsColorTag}))
.pipe(handlebarsFilter.restore)
.pipe(mailchimpFilter)
.pipe($.replace(primaryColor, mailchimpColorTag))
.pipe($.debug({title: 'Applying ' + mailchimpColorTag}))
.pipe(mailchimpFilter.restore)
.pipe($.replace(template_language, ''))
.pipe(gulp.dest('dist'));
}
In my windows store app, I allow users to open up a file, it does not exist locally then app will download it and save it the local folder of the app and then try to open it using the code below.
This works intermittently, other time the call returns false.
var launcherOption = new LauncherOptions();
launcherOption.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.Default;
launcherOption.DisplayApplicationPicker = userSettings.ShowApplicationPicker;
bool success;
// fileResponse.File is a StorageFile object
if (fileResponse.OpenAs == ContentOpenOption.LocalFile)
success = await Launcher.LaunchFileAsync(fileResponse.File, launcherOption);
else
success = await Launcher.LaunchUriAsync(fileResponse.WebUri, launcherOption);
Things I have checked for:
The file is not restricted by windows ( eg: I am testing with txt, jpg files, not exe, bin, bat )
My app is visible at the time this call is made
The call is made on the UI Thread by using the code below:
var launcherOption = new LauncherOptions();
launcherOption.DesiredRemainingView = Windows.UI.ViewManagement.ViewSizePreference.UseHalf;
launcherOption.DisplayApplicationPicker = userSettings.ShowApplicationPicker;
var dispatcherObject = CoreApplication.MainView.CoreWindow.Dispatcher;
if (dispatcherObject != null && dispatcherObject.HasThreadAccess == false)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
Windows.UI.Core.CoreDispatcherPriority.Normal,
async () =>
{
if (fileResponse.OpenAs == ContentOpenOption.LocalFile)
success = await Launcher.LaunchFileAsync(fileResponse.File, launcherOption);
else
{
launcherOption.TreatAsUntrusted = true;
success = await Launcher.LaunchUriAsync(fileResponse.WebUri, launcherOption);
}
});
}
else
{
if (fileResponse.OpenAs == ContentOpenOption.LocalFile)
success = await Launcher.LaunchFileAsync(fileResponse.File, launcherOption);
else
{
launcherOption.TreatAsUntrusted = true;
success = await Launcher.LaunchUriAsync(fileResponse.WebUri, launcherOption);
}
}
if (!success)
{
content.IsContentUpdating = false;
content.ContentStatus = string.Empty;
logger.LogMessage(string.Format("Unable to open file. {0}",
content.Name), LoggingLevel.Error);
}
}
Made sure that the file is not blocked by windows by checking it's properties.
Any other ideas what I might be missing here?