tooling code
this is my of development tool codes
file name sort
['2.png','3.png',...,'10.png','1.png','11.png']
I found this at nodejs server,i need it to sort properly.And I’m going to get the last one.
code:
// need to download request. yarn or npm
var request = require("request");
var fs = require("fs");
let path = require("path");
let dirname = "./images/";
function readFile(url, callback) {
fs.readdir(url, (err, files) => {
if (err) throw err;
let array = [];
files.forEach((filename) => {
// 拼接获取绝对路径,fs.stat(绝对路径,回调函数)
let absolute = path.join(url, filename);
let stat = fs.statSync(absolute);
if (stat.isFile()) {
array.push(filename);
} else {
readFile(absolute);
}
});
// You Notice here, The core code.
callback &&
callback(
array
.sort((a, b) => parseInt(a) - parseInt(b))
[array.length - 1].replace(".png", "") - 0
);
});
}
readFile(dirname, function (value) {
console.log(value);
});
but Sorting is more than that
- usually
let newArr = arr.sort(function (a, b) {
return a - b;
});
- There’s actually a special method
【localeCompare
】
arr.sort(function(a,b){return a.localeCompare(b)})
- localeCompare If it’s in Chinese
a.localeCompare(b,'zh-CN')
Use the Request to download the file
I have a some web images need download,I decision use nodejs.
code:
var request = require("request");
var fs = require("fs");
request(img_src).pipe(fs.createWriteStream("./images/logo.jpg"));
【More interesting code,Focus on song yu】learn and live!