fs.readFileSync returning weird encoding - javascript

I'm trying to use readFileSync to copy the contents of a Javascript file and then place it into an HTML file. However when I do so the outputted code is getting encoded and causing errors when the JS runs. For example = is getting encoded into =.
I've used different variations for the encoding like so
fs.readFileSync('dist/' + v + '.min.js')
fs.readFileSync('dist/' + v + '.min.js', 'utf8')
and the output doesn't change.
I'm using Webpack and the HtmlWebpackPlugin to read the file and serve it to a Handlebars template. When I log out the contents of the file it looks correct, so it's looking like Handlebars is mashing up the text for some reason.
Thanks for any help!

Related

Hash a entire folder instead of a single file

I'm using this code to hash a single file:
const fs = require('fs');
let result = digest(fs.readFileSync('/users/ispedro/desktop/Test.PDF'));
console.log('Huella Digital MD5: ' + result)
I am trying to achieve the same but of all the files included in a folder, so that the output would be something like this:
The file (name of the file) generates the following MD5 hash: 175GKG3K6UZ6GAEE64BFKUN0MR
I have tried with various codes but have not succeeded ... any ideas please?
Update:
What I want to do is that the script reads the contents of a folder on the desktop without having to compress it in zip, so that I can remove or put files and when executing the script it returns the MD5 hash of those that are currently inside. I have tried to copy part of the code from this link npmjs.com/package/folder-hash which I think does exactly that but I can't get the script to work ...
Thank you very much to all.

How to append data to txt in javascript?

I'm writing a program, which needs to take some JSON from text file, then modify it and put it back to the same file, something like overwriting. I don't have problem with reading from file and modifying data, but I was searching long and found nothing about writing into files. If it's important - it's server-side file.
Ex. text file: {"name":"John","age":20}
Result which I need: {"name":"John","age":21}
You can use the fs module in node to write to a file!
information is located here on it https://www.w3schools.com/nodejs/nodejs_filesystem.asp
The two methods you will want to look at is .writeFile or .appendFile depending on your specific need.

How do I HTTP GET a .js file and extract 'exports' variables?

I am writing a site in Laravel to complement a game written in Node. It pulls information directly from the game's .js files stored on GitHub and the plan is to use Vue to generate some nice HTML to display the data.
The .js files are of the form:
'use strict'
let x = {...};
exports.x = x;
I can import the files using a PHP request (simply using 'file') and pass them to JS with either jQuery.getScript or axios.get (so far). However, I am having real trouble coming up with a way to extract the 'x' values here under exports. If I were writing a JS app in node, I would simply do the following:
var xFile = require('xFile');
var x = xFile.x;
However, I can't figure out how to do that here as both GET methods return a string, not a JS file. JSON.parse() doesn't work, and I would like to come up with a solution that doesn't just replace the non-JSON text as I would need a reusable solution for other files. I don't suppose anybody has any ideas?
Thanks so much!
You could try something like below.
you could create the script tag dynamically and attach the script in the body and add your javascript code using innerHTML.
You call this script in your ajax response code.
let script = document.createElement('script');
script.innerHTML = 'alert("Hi")';
document.querySelector('body').appendChild(script);
I managed to figure it out! It's a little janky, but you can run a node file in PHP with the exec command. I just wrote a node file to import the file and return the useful data. This probably isn't an optimal solution, but it works for me since I'm much more confident with JS than with PHP.

convert a HTML to a JS file so i can unit test using mocha.js

I am want to convert an HTML file to a JS file so i can run a unit test using Mocha.JS
what I am testing for is to see if there are any double quotes (") in the HTML document
I'm kinda at a loss after googling for a few hours so if anyone can help it would be very much appreciated
MAny thanks in advance
Not sure if this is what you want but I'll do my guess. This is node.js code:
const fs = require('fs')
const contents = fs.readFileSync('index.html')
const thereAreDoubleQuotesInHtmlFile = contents.includes('"')
// test (with some pseudo-assertion-library)
assertTrue(thereAreDoubleQuotesInHtmlFile)
HTML and JavaScript are completely different things that serve completely different purposes. You can't convert one into the other.
If you want to test, from JavaScript, the contents of the HTML file, then write a test (in JavaScript) which reads the HTML file and then tests the resulting string (possibly after running it through a DOM parser so you can test using DOM methods).

Generate a Word document in JavaScript with Docx.js?

I am trying to use docx.js to generate a Word document but I can't seem to get it to work.
I copied the raw code into the Google Chrome console after amending line 247 to fix a "'textAlign' undefined error"
if (inNode.style && inNode.style.textAlign){..}
Which makes the function convertContent available. The result of which is an Object e.g.
JSON.stringify( convertContent($('<p>Word!</p>)[0]) )
Results in -
"{"string":
"<w:body>
<w:p>
<w:r>
<w:t xml:space=\"preserve\">Word!</w:t>
</w:r>
</w:p>
</w:body>"
,"charSpaceCount":5
,"charCount":5,
"pCount":1}"
I copied
<w:body>
<w:p>
<w:r>
<w:t xml:space="preserve">Word!</w:t>
</w:r>
</w:p>
</w:body>
into Notepad++ and saved it as a file with an extension of 'docx' but when I open it in MS Word but it says 'cannot be opened because there is a problem with the contents'.
Am I missing some attribute or XML tags or something?
You can generate a Docx Document from a template using docxtemplater (library I have created).
It can replace tags by their values (like a template engine), and also replace images in a paid version.
Here is a demo of the templating engine: https://docxtemplater.com/demo/
This code can't work on a JSFiddle because of the ajaxCalls to local files (everything that is in the blankfolder), or you should enter all files in ByteArray format and use the jsFiddle echo API: http://doc.jsfiddle.net/use/echo.html
I know this is an older question and you already have an answer, but I struggled getting this to work for a day, so I thought I'd share my results.
Like you, I had to fix the textAlign bug by changing the line to this:
if (inNode.style && inNode.style.textAlign)
Also, it didn't handle HTML comments. So, I had to add the following line above the check for a "#text" node in the for loop:
if (inNodeChild.nodeName === '#comment') continue;
To create the docx was tricky since there is absolutely no documentation on this thing as of yet. But looking through the code, I see that it is expecting the HTML to be in a File object. For my purposes, I wanted to use the HTML I rendered, not some HTML file the user has to select to upload. So I had to trick it by making my own object with the same property that it was looking for and pass it in. To save it to the client, I use FileSaver.js, which requires a blob. I included this function that converts base64 into a blob. So my code to implement it is this:
var result = docx({ DOM: $('#myDiv')[0] });
var blob = b64toBlob(result.base64, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
saveAs(blob, "test.docx");
In the end, this would work for simple Word documents, but isn't nearly sophisticated for anything more. I couldn't get any of my styles to render and I didn't even attempt to get images working. I've since abandoned this approach and am now researching DocxgenJS or some server-side solution.
You may find this link useful,
http://evidenceprime.github.io/html-docx-js/
An online demo here:
http://evidenceprime.github.io/html-docx-js/test/sample.html
You are doing the correct thing codewise, but your file is not a valid docx file. If you look through the docx() function in docx.js, you will see that a docx file is actually a zip containing several xml files.
I am using Open Xml SDK for JavaScript.
http://ericwhite.com/blog/open-xml-sdk-for-javascript/
Basically, on web server, I have a empty docx file as new template.
when user in browser click new docx file, I will retrieve the empty docx file as template, convert it to BASE64 and return it as Ajax response.
in client scripts, you convert the BASE64 string to byte array and using openxmlsdk.js to load the byte array as an javascript OpenXmlPackage object.
once you have the package loaded, you can use regular OpenXmlPart to create a real document. (inserting image, creating table/row ).
the last step is stream it out to end user as a document. this part is security related. in my code I send it back to webserver and gets saved temporarily. and prepare a http response to notify end user to download it.
Check the URL above, there are useful samples of doing this in JavaScript.

Categories