Node.j中path模块对路径的操作

时间:2021-10-20 13:36:48

一.path模块 https://nodejs.org/docs/latest/api/path.html#path_path_join_paths

1.join方法 ==> 该方法将多个参数值字符串结合成一个路径字符串,使用方式如下:

path.join([path1], [path2], [...])

2. __dirname变量值代表程序运行的根目录。

var joinPath = path.join(__dirname, 'a', 'b', 'c');
console.log(joinPath); // F:\learning\CPC爬虫\a\b\c

3.下载某图片到指定目录

const request = require('superagent')
const cheerio = require('cheerio')
const fs = require('fs-extra')
const path = require('path') function download() {
const url2 = "https://imgsa.baidu.com/forum/w%3D580/sign=cbeba091a5014c08193b28ad3a7a025b/1ba6b90e7bec54e7141e3726b5389b504ec26ab4.jpg"
const filename = url2.split('/').pop()
const req = request.get(url2)
req.pipe(fs.createWriteStream(path.join(__dirname, 'images', filename)))
}