常用代码片段

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

  1. usually
let newArr = arr.sort(function (a, b) {
  return a - b;
});
  1. There’s actually a special method

localeCompare

arr.sort(function(a,b){return a.localeCompare(b)})

  1. 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!




如果你遇到了前端难题,或者需要一对一帮扶服务,请到淘宝搜索店铺:前端在线或扫下面二维码

  转载规则


《常用代码片段》宋宇采用知识共享署名 4.0 国际许可协议进行许可。
 上一篇
vimvim
一个很不错的 linux 编辑器。 base 打开文件vi /path/file.txt or vim /path/file.txt 进入编辑模式i,要退出的话是 ESC 保存和退出:w //保存但不退出:q //不保存并退出:q!
2020-12-23
下一篇 
vue Virual DOMvue Virual DOM
vue 虚拟 domVirual DOM 是用 JS 对象记录一个 dom 节点的副本,当 dom 发生更改时候,先用虚拟 dom 进行 diff,算出最小差异,然后再修改真实 dom。vue 的 virtual dom 的 diff 算法
2020-12-23
  目录