NWJS can't re-save file - node.js

I have nwjs app, and i want save file. So I have code like this:
try {
fs.writeFileSync(this.value, data);
} catch (e) {
alert(e);
}
and it's good. But when I want re-save data in the same file, it's not working. No error but no new data in file to.

You should refer this documentation.
Try below code.
var fs = require('fs');
fs.writeFile("/tmp/test", "Hello!", function(e) {
if(e) {
return console.log(e);
}
console.log("The file is saved!");
});
This link will be useful too :)
Hope it will help you :)

I have an input like <input type="file" nwsaveas="myFile.txt"> and can't re-save file because of this issue:
https://github.com/nwjs/nw.js/wiki/file-dialogs#choosing-the-same-directory-multiple-times
To solve it I reset the input value to empty string after fs.writeFile().

Related

Writing to file after modifying with cheerio on node

I am running a node script that reads a .svg font file, passes it as a string variable to Cheerio, modifies it and attempts to write to disk
The problem is that although the script seems to work, the output file is identical to the input file, as if no modification happened.
It looks to me as if the original "svgFont" variable that I pass to cheerio is not modified at all.
So I would need to either pass the modifications back to it, or output from cheerio directly to fs write. But I can't see how to.
const cheerio = require('cheerio');
var fs = require('fs');
// read the svg font
fs.readFile('font.svg', function read(err, data) {
if (err) {
throw err;
}
// convert to string and pass to cheerio
var svgFont = data.toString();
const $ = cheerio.load(svgFont, {
normalizeWhitespace: true,
xmlMode: true
});
// loop all glyph tags
$("glyph").each(function(i,el){
// modify things
});
// Finally write the font with the modified paths
fs.writeFile("outFont.svg", svgFont, function(err) {
if(err) {
throw err;
}
console.log("The file was saved!");
});
});
You could use the fs-cheerio package to write to files. In your code the original variable is not being modified. It is the parsed cheerio representation that gets modified.
The right answer is to pass the cheerio object '$' that contains all the modifications using, in this case, .xml(), as this is a .svg file I am reading. For example:
// Finally write the font with the modified paths
fs.writeFile("outFont.svg", $.xml(), function(err) {
if(err) {
throw err;
}
console.log("The file was saved!");
});

Check for req.files object empty

I am uploading file through express-fileupload. My file gets uploaded successfully if I am not checking for req.files as empty. But I am getting one error as when I am going to check for req.files as empty. I am posting my code as referenace.
if(req.files.length > 0){
console.log('file is exist');
var file_name = req.files.filetoupload;
file_name.mv("public/uploads/"+ file_name.name, function(err){
if(err){
console.log(err);
var profile_pic_name = '';
} else {
var profile_pic_name = file_name.name;
}
});
}
else
{
console.log('file not exist');
var profile_pic_name = '';
}
So when I am trying to upload a file it goes in else section and prints "file not exist" on console. So my main concern is how to check if req.files is empty or not.
Thanks in advance
Sorry I don't know if I understood correctly your question.
Try something like that:
req.files && req.files.length
I hope this help, If this doesn't meet your necessity let me know
You can easily achieve that using a conditional ternary operator.
For instance, below sample code print "Non Empty File" if req.files exists or "Empty file" if req.files is empty.
req.files ? console.log('Non Empty File') : console.log('Empty file');
You can do something like this and find out if the file exists or not.
if (!req.files) {
// File does not exist.
console.log("No file");
} else {
// File exists.
console.log("File exists");
}
try {
var file_name = req.files.filetoupload;
file_name.mv("public/uploads/"+ file_name.name)
} catch (error) {
res.send(`File not found`)
}
Use the try and catch method and it works...

Meteor upload image blob

I use a ImageCropper (https://www.npmjs.com/package/cropper) and this generated by a cut-out image, the blob object. This Blob Object I would now like to also upload how is this possible?
My current not working approach:
Client:
$(elem).cropper('getCroppedCanvas').toBlob(function (blob) {
var file = new File([blob], "name");
Meteor.call('file-upload', file);
});
Server:
Meteor.methods({
'file-upload': function (file) {
var fs = Meteor.npmRequire('fs');
fs.writeFile("/tmp/test.jpg", file, function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
}
});
See my answer in this SO post.
I highly recommend Slingshot. It's really easy to use and uploads blobs.

How to guarantee non-existance of a file before creating?

fs.exists is now deprecated for a decent reason that I should try to open a file and catch error to be sure nothing is possible to delete the file in between checking and opening. But if I need to create a new file instead of opening an existing file, how do I guarantee that there is no file before I try to create it?
You can't. You can however, create a new file or open an existing one if it exists:
fs.open("/path", "a+", function(err, data){ // open for reading and appending
if(err) return handleError(err);
// work with file here, if file does not exist it will be created
});
Alternatively, open it with "ax+" which will error if it already exists, letting you handle the error.
module.exports = fs.existsSync || function existsSync(filePath){
try{
fs.statSync(filePath);
}catch(err){
if(err.code == 'ENOENT') return false;
}
return true;
};
https://gist.github.com/FGRibreau/3323836
https://stackoverflow.com/a/31545073/2435443
fs = require('fs') ;
var path = 'sth' ;
fs.stat(path, function(err, stat) {
if (err) {
if ('ENOENT' == err.code) {
//file did'nt exist so for example send 404 to client
} else {
//it is a server error so for example send 500 to client
}
} else {
//every thing was ok so for example you can read it and send it to client
}
} );

Different results from asynchronous and synchronous reading

I have a fairly simple script that attempts to read and then parse a JSON file. The JSON is very simple and I am pretty sure it is valid.
{
"foo": "bar"
}
Now, I have been trying to read it with fs.readFile. When read no errors occur and the returned data is a string. The only problem is that the string is empty.
I repeated my code but used fs.readFileSync, this returned the file perfectly using the same path. Both had a utf-8 encoding specified.
It is very simple code, as you can see.
fs.readFile('./some/path/file.json', 'utf8', function(err, data) {
if(!err) {
console.log(data); // Empty string...
}
});
console.log(fs.readFileSync('./some/path/file.json', 'utf8')); // Displays JSON file
Could it be permissions or ownership? I have tried a permission set of 755 and 777 to no avail.
I am running node v0.4.10. Any suggestions to point me in the right direction will be much appreciated. Thanks.
Edit: Here is a block of my actual code. Hopefully this will give you a better idea.
// Make sure the file is okay
fs.stat(file, function(err, stats) {
if(!err && stats.isFile()) {
// It is okay. Now load the file
fs.readFile(file, 'utf-8', function(readErr, data) {
if(!readErr && data) {
// File loaded!
// Now attempt to parse the config
try {
parsedConfig = JSON.parse(data);
self.mergeConfig(parsedConfig);
// The config was loaded and merged
// We can now call the callback
// Pass the error as null
callback.call(self, null);
// Share the news about the new config
self.emit('configLoaded', file, parsedConfig, data);
}
catch(e) {
callback.call(self, new Error(file + ': The config file is not valid JSON.'));
}
}
else {
callback.call(self, new Error(file + ': The config file could not be read.'));
}
});
}
else {
callback.call(self, new Error(file + ': The config file does not exist.'));
}
});
This is pretty weird.
The code looks.
var fs = require('fs');
fs.readFile('./jsonfile', 'utf8', function(err, data) {
if(err) {
console.error(err);
} else {
console.log(data);
parsedConfig = JSON.parse(data);
console.log(parsedConfig);
console.log(parsedConfig.foo);
}
});
Json file:
{
"foo": "bar"
}
output :
$ node test_node3.js
{
"foo": "bar"
}
{ foo: 'bar' }
bar
This is on node 0.4.10 , but i'm pretty sure it should work on all node version.
So why your data is empty ? You should check err in this case (like mine) and post the output if any. If you have no error, you may fill a bug on github

Resources