利用nodejs把指定的文件名生成对应的目录

a.js如下
const fs = require('fs')
const path = require('path')
const os = require('os')
const o777 = parseInt('0777', 8)

function getRootPath (p) {
    p = path.normalize(path.resolve(p)).split(path.sep)
    if (p.length > 0) return p[0]
    return null
}
const INVALID_PATH_CHARS = /[<>:"|?*]/

function invalidWin32Path (p) {
    const rp = getRootPath(p)
    p = p.replace(rp, '')
    return INVALID_PATH_CHARS.test(p)
}


function mkdirsSync (p, opts, made) {
    if (!opts || typeof opts !== 'object') {
        opts = { mode: opts }
    }

    let mode = opts.mode
    const xfs = opts.fs || fs

    if (process.platform === 'win32' && invalidWin32Path(p)) {
        const errInval = new Error(p + ' contains invalid WIN32 path characters.')
        errInval.code = 'EINVAL'
        throw errInval
    }

    if (mode === undefined) {
        mode = o777 & (~process.umask())
    }
    if (!made) made = null

    p = path.resolve(p)

    try {
        xfs.mkdirSync(p, mode)
        made = made || p
    } catch (err0) {
        if (err0.code === 'ENOENT') {
            if (path.dirname(p) === p) throw err0
            made = mkdirsSync(path.dirname(p), opts, made)
            mkdirsSync(p, opts, made)
        } else {
            // In the case of any other error, just see if there's a dir there
            // already. If so, then hooray!  If not, then something is borked.
            let stat
            try {
                stat = xfs.statSync(p)
            } catch (err1) {
                throw err0
            }
            if (!stat.isDirectory()) throw err0
        }
    }

    return made
}

fs.ensureDirSync = mkdirsSync;


let BUG = `weidian`

let files = fs.readFileSync('./a.txt').toString().split(os.EOL);
console.log(files);
let filesFilter = [...new Set(files)]

for (let filesFilterElement of filesFilter) {
    if(filesFilterElement != ""){
        let arr = filesFilterElement.split(path.sep)
        arr.splice(0, 2)
        let fileName = arr.splice(arr.length - 1, 1)[0]
        let currentPath = path.resolve()
        let targetPath = path.join(currentPath, BUG, arr.join('/'))
        fs.ensureDirSync(targetPath)

        let fromPath = path.join(currentPath, fileName);
        let toPath = path.join(targetPath, fileName)
        fs.copyFileSync(fromPath, toPath)
        console.log(`${fromPath} ===>> ${toPath}`);
    }
}
a.txt放置需要创建的文件,内容如下(idea系列ctrl+shift+c可以拷贝文件路径)



确保当前目录有如下两个文件,然后node ./a.js

生成如下目录


你可能感兴趣的:(前端开发笔记)