fs.writeFile() only saving part of string - javascript

I'm creating a text editor using node-webkit. When the user clicks a "Save" menu item, I get write a plain text file to disk using the fs.writeFile() method:
fs.writeFile(file, txt, function (err) {
if (err) throw err;
console.log("file saved");
});
However, it's not saving the entire string passed through the "txt" variable. It's only saving the first 300 characters or so to the file.
I've tried using this method, and the synchronous method fs.writeFileSync. Both are having the same problem. I've tried logging the txt string passed to the method to make sure there's nothing wrong there.
Any ideas why I'm not getting the full text in my saved file?

According to this post: https://groups.google.com/forum/#!topic/node-webkit/3M-0v92o9Zs in the node-webkit Google group, it is likely an encoding issue. Try changing the encoding. I was having the same problem and changed my encoding to utf16le, as specified in that thread, and it fixed the issue; the whole string was written to the file.
My code is now: fs.writeFileSync(path, data, {encoding:'utf16le'});

Related

MVC 5 - jQuery - Displaying FileContentResult Without Downloading

I'm trying to display the results of a FileContentResult MVC Action in an object tag. I can easily display files that have a preview option; .txt, .pdf, .jpg, etc. The problem comes in when there are files that don't have a preview option. My problem isn't figuring out which type of files work, my problem is figuring out how to stop them from downloading (or trying to download).I've tried making an ajax call to grab the file, which I can do, but I don't know how to display it after that. Any tips or ideas? This is the object I get back from the jquery call.
It's essentially just the mimetype, the name, and the byte array. Here's a snap of the object in MVC:This doesn't seem like it should be as hard as it seems. Am I just missing something obvious? Thanks!
I realized what I could do in order to get around this problem, I won't submit this as the answer in case other people actually do have ideas on how to work around this. I think my solution is pretty self-explanatory, but I'll go into a little detail.
public ActionResult GetFile()
{
HBSFile file = new Common.Business.FileIO.FileIO(Server.MapPath("~/Content/Images"), "testdoc.docx").Read();
if (file.CanBePreviewed)
{
return File(file.Stream, file.ContentType);//, file.FileName + "." + file.Extension);
}
return null;
//return Json(new Test(File(file.Stream, file.ContentType, file.FileName + "." + file.Extension), file.CanBePreviewed), JsonRequestBehavior.AllowGet);
}
The HBSFile object is simply the properties of the file. file.Stream is a byte array. To get around my problem, I simply check to see if the file can be previewed or not. If it can be, I'll return a FileContentResult.

Piping console.log() contents to a .txt file in Node.js

I have a Node.js file that outputs a bunch of test results, easily >1000 lines, to Terminal. The file looks something like this:
launchChromeAndRunLighthouse('https://www.apple.com/', flags).then(results => { console.log(results); });
The console.log() is only there because I couldn't figure out another way to view the results. I need a way to create a file through Node.js, not the command line, that contains all of the CLI output/results.
I thought that fs.appendFile('example.txt', 'append this text to the file', (err) => {}); could be of use, but what I need to "append" to the file is the function's results. When I try that, the file only contains [object Object] instead of the actual results of the tests.
I'm a beginner to Node, any advice is highly appreciated.
You are close, but you need to include the appendFile inside of your other function. This assumes that your 'results' object is of the string type. If not then you need to get the string version of this object.
The lighthouse docs specify the format of the log information that is returned. If you add output: json to the flags object then you can use it lik
launchChromeAndRunLighthouse('https://www.apple.com/', flags).then(results => {
fs.appendFile('example.txt', JSON.stringify(results), (err) => {
console.log('error appending to file example.txt');
});
});

Node/Javascript Redirect Not Working?

I have built a form to add some dummy data to a Mongo collection for testing purposes. The function to add the data seems to be working ok in that the data is being added ok, but, for some reason, the redirect command at the end of the function is not doing its thing. The data comes from a bog standard HTML form. Here is the code for adding the data:
router.post('/addacc',function(req,res){
var sljEdate = "";
var pljEdate = "";
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/stc';
MongoClient.connect(url,function(err,db){
if(err){
console.log("Connection Error");
}else{
console.log("connected to mongo");
var collection = db.collection('account');
var query = {accountID: req.body.acc_id,companyName: req.body.acc_name,companyEmail:req.body.acc_email,companyPhone:req.body.acc_phone,companyPostCode:req.body.acc_postcode,
photographers: {phtID:"",phtName:"",phtPhone:"",phtEmail:"",phtLoc:"",preferredContact:"",lastJob:"",pljEpoch:pljEdate,phtNotes:""},
schools: {schoolID:"",schoolName:"",schoolPhone:"",schoolEmail:"",schoolPostCode:"",lastJob:"",sljEpoch:sljEdate,notes:""}};
collection.insert(query,function(err,result){
if(err){
console.log("Error inserting Account record",err);
}else{
console.log("Data Insert Success");
res.redirect("/forms");
}
db.close();
});
}
});
});
I added lines to log to the console in a few places so that I could check progress and they all fire, including the final 'Data Insert Success' one. The res.redirect which follows it, however, does nothing. In the browser the URL remains as '/addacc', though the node console shows a subsequent GET for the '/forms' URL.
I've tried a few variations for the redirect, using e.g. res.send("test") just to try and output something, also a res.render function, but none of them seem to work.
I'm pretty sure that I have missed something simple, but I've been staring at the code for too long and I can't see anything wrong with it. In fact, I've had nearly identical code working lots of times. The only thing I'm doing differently this time is that I'm inserting into a Mongo collection which includes embedded documents, but the data insert is not the problem as the data gets in fine.
Help please!
Ok, it seems that the Node problem above was a bit of a red herring. The redirect is actually working ok (MrWillihog's comment above is duly noted for future reference anyway). I thought it must be as all the response codes on the npm console checked out fine. The problem is actually to do with the rendering of the Jade template. Specifically something to do with the the file layout.jade which I use to set out the HTML head. For some reason (yet to be determined) things work fine when calling the /forms page directly in the URL. The file forms.jade starts in the standard way with
extends layout
block content
With the opening BODY tag in layout.jade the page fails to load properly when called from the redirect: the layout.jade file renders (I put an H1 in there to check), but forms.jade doesn't.
I moved the BODY down in to forms.jade (under block.content) and it started working though, interestingly, the URL in the address bar remains as '/accadd'
Again I'm a bit stumped as I have used this pattern quite a few times with no issue. I'm guessing that I've just forgotten something simple. I'll keep digging until I find the answer, but at least now I should be looking in the right place.

How to write to js file at specific location on key value pairs?

I am writing to a js file using protractor as follows :
index.js
var outputFile = '../Actions/data_write.js';
var username = "someusername";
var password = "somepassword";
var fs = require('fs');
var text = "userCredentials : {username : '"+username+"', password : '"+password+"'};";
fs.writeFile(outputFile, text, function(error){
if(error){
console.log(error);
}else{
console.log('data saved to '+outputFile);
}
});
My issue is I am not able to figure out how to write this data at specific location. So like right now the text is written to the entire file by replacing the old content. I want to write it at say at specific location, say I have multiple data with username and password defined in array in this file. I want to write to that specific array.
FileSystem APIs do not provide support for editing a file, rather focus on file operations.
You can read the older content into an object or a string, then navigate through it to figure out the right position for insertion, add your new content, and then write the transformed data back into the file.
If your app involves intensive file content modification with seeking to and fro, you may consider writing a native add-on with memory mapped file, for efficiency and performance.
Hope this helps.

node.js does not recognise the url in the unfluff module

Any help will be appreciated.
I need to extract data from websites and found that node-unfluff does the job (see https://github.com/ageitgey/node-unfluff). There is two ways to call this module.
First, from command line which works!
Second, from node js which doesn't work.
extractor = require('unfluff');
data = extractor('test.html');
console.log(data);
Output : {"title":"","lang":null,"tags":[],"image":null,"videos":[],"text":""}
The data returns an empty json object. It appears like it cannot read the test.html.
It seems like it doesn't recognise test.html. The example says, "my html data", is there a way to get html data ? Thanks.
From the docs of unfluff:
extractor(html, language)
html: The html you want to parse
language (optional): The document's two-letter language code. This
will be auto-detected as best as possible, but there might be cases
where you want to override it.
You are passing a filename, and it expects the actual HTML of the file to be passed in.
If you are doing this in a scripting context, I'd recommend doing
data = extractor(fs.readFileSync('test.html'));
however if you are doing this in the context of a server or some time when blocking will be an issue, you should do:
fs.readFile('test.html', function(err, html){
var data = extractor(html);
console.log(data);
));

Categories