Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.
In this article, we’ll look at some solutions to common JavaScript problems.
Secure Random Token in Node.js
We can generate a secure random token easily with Node.js.
For instance, we can write:
require('crypto').randomBytes(48, (err, buffer) => {
const token = buffer.toString('hex');
});
We import the crypto
library and call its randomBytes
method.
It calls the callback with a buffer
which we can convert to a hex string.
Perform .join on a Value in an Array of Objects
We can call join
on a value in an array of objects if we call map
to get the values first,
For instance, if we have:
const students = [
{ name: "james", age: 12 },
{ name: "alex", age: 14 },
{ name: "mary", age: 11 }
]
Then we can use map
and join
by writing:
students.map(s => s.name).join(",");
We get the name
property of each object in the array and call join
to join them with a comma.
Split String Only on First Instance of Specified Character and Get the Substring After it
We can use capturing parentheses in our regex that we use with split
.
For instance, we can write:
"foo_bar_baz".split(/_(.+)/)[1]
This pattern will only capture the first underscore.
_.+
means the underscore and everything after it.
Then we get 'bar_baz'
returned from it.
We can also use substring
and indexOf
to do the same thing.
For example, we can write:
`const str = "foo_bar_baz";
`const newStr = str.substring(str.indexOf('_') + 1);
indexOf
gets the index of the first instance of _
, then we add 1 to get the rest of the string.
Resolve Promises One After Another
To resolve promises one after another, we can write an async
function.
For instance, we can write:
async function writeFiles(texts) {
for(const text of texts) {
await writeFile(text);
}
};
We can use async
and await
with the for-of loop to write files.
writeFile
is a function that returns a promise.
Also, we can promisify existing async calls in Noe apps.
We can use Bluebird to do that:
const Promise = require("bluebird");
const fs = Promise.promisifyAll(require("fs"));
const readAll = Promise.resolve(files).map(fs.readFile,{ concurrency: 1 });
readAll.then((allFileContents) => {
// do stuff to read files.
});
We convert the fs.readFile
method to a promise so we can call then
on it to chain them.
Get a URL without the Query String
To get a URL without the query string part, we can use the split
method.
For instance, we can write:
window.location.href.split('?')[0]
We call split
with the question mark and get the first part.
Also, we can write:
const url = `${location.origin}${location.pathname}${location.hash}`;
to get all the parts before the query string and concatenate them together.
location.origin
gets us the domain part of the URL.
location.pathname
gets the path of the IRL.
And location.hash
gets the hash part.
Remove Time from Date with Moment.js
To remove time from a date with moment.js, we can call format
to format a date string.
For example, we can write:
moment().format('LL');
We can also use:
moment().startOf('day')
to get the day.
Removing an Item from a Select Box
We can remove an item from a select box by using the jQuery.
For instance, if we have the given select element:
<select name="fruit" id="fruit">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="grape">Grape</option>
</select>
Then we can remove it by writing:
$("#fruit option[value='grape']").remove();
We can remove the option with the value grape
by using the selector.
Access iFrame Parent Page Using jQuery
We can pass in the second argument to the $
function to specify that we want to access the parent window.
For instance, we can write:
$('#parentEl', window.parent.document).html();
We pass in the window.parent.document
value to select the element with ID with parentEl
from the parent window instead of the current one.
Conclusion
We can use the crypto
module to create a random token.
To call join on a property of objects in the array, we can call map
to get the values in an array first.
Also, we can get the URL without a query string by using various properties of the location
object.
We can remove an option element by its selector.