Phonegap file writer is not working, cannot truncate file content - html

I am using phonegap file reading functionality, once i read the content and i will do some functionality with that content, once that over i am calling file truncate functionality. In that i can't truncate any value. Help me to fix this issue.
removeFileContent();
function removeFileContent(){
console.log("Inside remove file content");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileTruncate, onProcessFailure);
};
function gotFileTruncate(fileSystem){
console.log("Inside get file path for remove content");
/** Function to get file path */
filePath = getFilePath(device.platform);
console.log("Device File Path to remove content-->"+this.filePath);
fileSystem.root.getFile(filePath, null, gotFileEntryTruncate, onProcessFailure);
}
function gotFileEntryTruncate(fileEntry){
globals.raiseLog("Inside file to truncate call");
globals.raiseLog("File Name-->"+fileEntry.name);
fileEntry.createWriter(gotFileWriter, onProcessFailure);
}
function gotFileWriter(writer){
globals.raiseLog("Inside file writer to truncate file content");
globals.raiseLog("Content length-->"+writer.length);
//writer.truncate(10);
writer.onwriteend = function(evt) {
writer.truncate(0);
writer.onwriteend = function(evt) {
};
};
writer.write("");
globals.raiseLog("Content length after truncate-->"+writer.length);
}
In the above gotFileWriter() if i check for writer.length its still showing some count. I dont know how come we can check the file gets empty. I having some text inside that file. Need to clear the file when i finish the reading of the file. I am calling removeFileContent() after i finish the reading functionality. Kindly help.

The way your code is written you may get a false positive that the file still has contents in it. Move your:
globals.raiseLog("Content length after truncate-->"+writer.length);
into your onwriteend function as the write call is async and may not finish before your log is printed.

Related

Gulp-rev-all leaves old revision file

I'm having problems with my gulp-rev-all task. Everytime I change the code, it will generate a new revision file, but leave the old one there.
Here is my gulp task:
var gulp = require('gulp');
var RevAll = require('gulp-rev-all');
gulp.task('js', function() {
var revAll = new RevAll();
return gulp.src(opt.Src + 'scripts.js')
// Add a hash to the file
.pipe(revAll.revision())
// Save the hashed css file
.pipe(gulp.dest(path.js))
// Write the manifest file
.pipe(revAll.manifestFile())
.pipe(gulp.dest(path.js + 'rev'));
});
So, this works like a charm.
It will give me a file with a rev (like: scripts.0ad8ecf1.js) and a manifest.json file.
The challange is, whenever I change my code, it will generate a new scripts.js file with a different hash and not overwrite or remove the old one. So, my folder looks like this now:
scripts.0ad8ecf1.js
scripts.7e3fa506.js
scripts.056ddda0.js
I can't seem to replace the old file for the new one.
Can anybody help me or point me in the right direction to accomplish this?
You need to delete your files with another plugin, since gulp-rev-all doesn't do this for you.
You could for example use the 'del' package (https://www.npmjs.com/package/del)
And then create a "delete Task" something like this:
var del = require('del');
/**
* Deletes all files inside the /foo/scripts/ folder
*/
gulp.task('purge:foo', function() {
return del.sync(['foo/scripts/**'], function (err, deletedFiles) {
if (err) {
console.log(err);
}
if (deletedFiles) {
console.log('Elements deleted:', deletedFiles.join(', '));
}
});
});

How to make gulp-newer work with gulp-rev?

The setup is as simple as this:
gulp.task('rev-js', function() {
return gulp.src('/js/main.js, {base: '.'})
.pipe(newer('_build'))
.pipe(rev())
.pipe(gulp.dest('_build'))
.pipe(rev.manifest())
.pipe(gulp.dest('_build/rev/js'));
});
gulp-newer obviously doesn't work here since the destination file gets a different name. Any workaround to make gulp-newer (or gulp-changed) work in this case?
In the gulp-newer options documentation I read that it supports passing in a configuration object instead of the destination. In that configuration object you can specify a mapping function from old to new files. So instead of
newer('_build')
you can write
newer({dest: '_build', map: mappingFn})
The mapping function takes the relative name of the file and expects it to return a translated name - see the index.js file. You can define a function that uses the previously generated rev-manifest.json manifest to look up the correct filename. Id put something along these lines in your build script (not tested):
gulp.task('rev-js', function() {
// get the existing manifest
// todo: add logic to skip this if file doesn't exist
var currentManifest = JSON.parse(fs.readFileSync('rev-manifest.json', 'utf8'));
// mapping function for gulp-newer
function mapToRevisions(relativeName) {
return currentManifest[relativeName]
}
return gulp.src('/js/main.js, {base: '.'})
.pipe(newer({dest: '_build', map: mapToRevisions}))
.pipe(rev())
.pipe(gulp.dest('_build'))
.pipe(rev.manifest())
.pipe(gulp.dest('_build/rev/js'));
});
May I suggest gulp-newy in which you can manipulate the path and filename in your own function. Then, just use the function as the callback to the newy(). This gives you complete control of the files you would like to compare.
This will allow 1:1 or many to 1 compares.
newy(function(projectDir, srcFile, absSrcFile) {
// do whatever you want to here.
// construct your absolute path, change filename suffix, etc.
// then return /foo/bar/filename.suffix as the file to compare against
}

how to modify config files using gulp

I use gulp to configure complex local setup and need to auto-edit files.
The scenario is:
determine if certain file contains certain lines after certain other line (found using regular expression)
if line is not found, insert the line.
optionally, delete some lines found in the file.
I need this to amend system configuration files and compile scenarios.
What would be the best way to do it in gulp?
Gulp is plain javascript. So what I would do if I were you is to create a plugin to pipe to the original config file.
Gulp streams emit Vinyl files. So all you really got to do is to create a "pipe factory" that transforms the objects.
It would look something like this (using EventStream):
var es = require('event-stream');
// you could receive params in here if you're using the same
// plugin in different occasions.
function fixConfigFile() {
return es.map(function(file, cb) {
var fileContent = file.contents.toString();
// determine if certain file contains certain lines...
// if line is not found, insert the line.
// optionally, delete some lines found in the file.
// update the vinyl file
file.contents = new Buffer(fileContent);
// send the updated file down the pipe
cb(null, file);
});
}
gulp.task('fix-config', function() {
return gulp.src('path/to/original/*.config')
.pipe(fixConfigFile())
.pipe(gulp.dest('path/to/fixed/configs');
});
Or you can use vinyl-map:
const map = require('vinyl-map')
const gulp = require('gulp')
const modify = map((contents, filename) => {
contents = contents.toString()
// modify contents somehow
return contents
})
gulp.task('modify', () =>
gulp.src(['./index.js'])
.pipe(modify)
.pipe(gulp.dest('./dist'))
})

fs.readstream to read an object and then pipe to writeable to file?

Currently I have a module pulling sql results like this:
[{ID: 'test', NAME: 'stack'},{ID: 'test2', NAME: 'stack'}]
I want to just literally have that written to file so i can read it as an object later, but i want to write it by stream because some of the objects are really really huge and keeping them in memory isnt working anymore.
I am using mssql https://www.npmjs.org/package/mssql
and I am stuck at here:
request.on('recordset', function(result) {
console.log(result);
});
how do I stream this out to a writable stream? I see options for object mode but i cant seem to figure out how to set it?
request.on('recordset', function(result) {
var readable = fs.createReadStream(result),
writable = fs.createWriteStream("loadedreports/bot"+x[6]);
readable.pipe(writable);
});
this just errors because createReadStream must be a filepath...
am I on the right track here or do I need to do something else?
You´re almost on the right track: You just dont need a readable stream, since your data already arrives in chunks.
Then, you can just create the writeable stream OUTSIDE of the actual 'recordset'-Event, else you would create a new stream everytime you get a new chunk (and this is not what you want).
Try it like this:
var writable = fs.createWriteStream("loadedreports/bot"+x[6]);
request.on('recordset', function(result) {
writable.write(result);
});
EDIT
If the recordset is already too big, use the row-Event:
request.on('row', function(row) {
// Same here
});

Flash Builder will not read local JSON file . .

So I've tried to build a small utility to view the contents of a JSON file in an easy-to-understand manner (for non-tech people).
I have Googled far and wide, high and low, but every example that shows how to consume a JSON file in Flash Builder uses the HTTP service, pointing to a file on the web.
Here I am, sitting in front of my MacBook, wondering why I can't make this work. In the documentation I've found (sort of relating to this issue), they always show Windows examples, and they seem to work fine:
C://me/projects/json/my_json.json
Perhaps I'm completely missing the obvious, but is this possible on a Mac as well?
I've tried
file:///Users/me/projects/json/my_json.json
That doesn't work. I've tried some "resolve to path" syntax, but the HTTP service does not seem to allow for anything but file paths in quotes.
Would anyone be able to pint me in the right direction?
Use the File API. It's really easy, here's a quick code sample:
// Get a File reference, starting on the desktop.
// If you have a specific file you want to open you could do this:
// var file:File = File.desktopDirectory.resolvePath("myfile.json")
// Then skip directly to readFile()
var file:File = File.desktopDirectory;
// Add a listener for when the user selects a file
file.addEventListener(Event.SELECT, onSelect);
// Add a listener for when the user cancels selecting a file
file.addEventListener(Event.CANCEL, onCancel);
// This will restrict the file open dialog such that you
// can only open .json files
var filter:FileFilter = new FileFilter("JSON Files", "*.json");
// Open the file browse dialog
file.browseForOpen("Open a file", [filter]);
// Select event handler
private function onSelect(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
// Cast to File
var selectedFile:File = e.currentTarget as File;
readFile(selectedFile);
}
private function onCancel(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
}
private function readFile(file:File):void
{
// Read file
var fs:FileStream = new FileStream();
fs.open(selectedFile, FileMode.READ);
var contents:String = fs.readUTFBytes(selectedFile.size);
fs.close()
// Parse your JSON for display or whatever you need it for
parseJSON(contents);
}
You hinted at this in your post about examples being for Windows and you being on a Mac but I'll state it explicitly here: you should always use the File API because it is cross platform. This code will work equally well on Windows and Mac.