var a = [34, 165, 11649, 4]; console.log(a.sort( ));Answer: if we execute this code, the output is
[11649, 165, 34, 4]To sort these numbers JavaScript first changes them into strings, then sorts them in dictionary order. To sort them as numbers, pass a function to a.sort that tells how to compare two numbers. This function should return a positive number when a > b , it should return a negative number when a < b , and it should return zero when a == b . The function that does this is defined as (a, b) => a - b; if a > b , a - b is positive, if a > b, a - b is negative, and if a == b , a - b is 0 . Here are the JavaScript statements:
var a = [34, 165, 11649, 4];
console.log(a.sort( (s, t) => {
if (s > t) {
return 1;
}
else if (s < t) {
return -1;
}
else {
return 0;
}
}));
localhost:3000/home_pageThe URL is "/home_page". Answer: route
// req is the request object. var route = req.url;
Reference: W3Schools Node.js File System Module
www.w3schools.com/nodejs/nodejs_filesystem.asp
| Action | fs Function |
|---|---|
| Read from File | readFile |
| Create file | open |
| Write to File | writeFile |
| Append to File | readFile |
| Delete File | unlink |
| Rename Files | rename |
This is a test line of data.
var fs = require("fs");
fs.readFile("data.txt", (err, data) => {
if(err) {
console.log("Error reading file data.txt");
}
else {
console.log(`Data line: ${data}`);
}
});
Data line: This is a test line of data.
var fs = require("fs");
var output = "Some sample file content.";
fs.writeFile("output.txt", output, (err) => {
if(err) {
console.log("Error writing to file.");
}
else {
console.log(
"File contents saved in output.txt file.");
}
});
// Append to file.
var fs = require("fs");
var line = "\nSome more sample file content.";
fs.appendFile("output.txt", line, (err) => {
if(err) {
console.log("Error appending to file.");
}
else {
console.log(
"File contents saved in output.txt file.");
}
});