node 之 file 文件的读取,写入,创建,删除

下面带有Sync的都是阻塞运行.

读取文件  readFile/readFileSync

// 非阻塞
fs.readFile(path.resolve(__dirname,'files/hellow.txt'), (err, data) => {
  console.log(data.toString());
})

// 阻塞
const data = fs.readFileSync(path.resolve(__dirname,'files/hellow.txt'))
console.log(data.toString());
console.log('程序运行完场');

打开文件 open/openSync

// 非阻塞
fs.open('./files/hellow1.txt', 'w+', (err, fd) => {
    if(err) throw err;
    console.log(fd)
})

获取文件信息 stat/statSync

fs.stat('./files/hellow.txt', (err, stats) => {
    if(err) throw err;
    console.log(stats.isFile()); // true
    console.log(stats.isDirectory()); // false
})

写入文件

fs.writeFile('./files/hellow2.txt', '我是一只小鸭子,咿呀咿呀呦', (err) => {
    if(err) throw err;
    // const file = fs.readFileSync('./files/hellow1.txt');
    // console.log(file.toString());

    fs.readFile('./files/hellow2.txt', (err, file) => {
        if(err) throw err;
        console.log(file.toString());
    })
})

删除文件

fs.unlink('./files/hellow1 copy.txt', (err) => {
    if(err) throw err;
    console.log('删除成功!');
})

 创建目录

fs.mkdir('./files/createdir', (err) => {
    if(err) throw err;
    console.log('文件创建成功!');
})

读取目录

fs.readdir('./files', (err, files) => {
    if(err) throw err;
    files.forEach(file => console.log(file))
    console.log('文件读取成功!');
})

删除目录

fs.rmdir('./files/createdir', (err) => {
    if(err) console.log(1);
    fs.readdir('./files', (err, files) =>{
        if(err) console.log(2);
        files.forEach(file => console.log(file))
    })
})

是否存在文件

fs.existsSync(path.resolve(__dirname, 'src/temp1')); // 返回布尔值

复制文件copyFile/copyFileSync

fs.copyFileSync(
  path.resolve(__dirname, 'src/pages'),
  path.resolve(__dirname, 'view/temp1')
)
// src/pages.html复制到view/temp1.html

综合案例:

将html的script里面的js代码抽离出来放入到单独的js文件中,然后再插入到html中。

const path = require('path');
const fs = require('fs');
const cheerio = require('cheerio');
const isExist = (path) => { // 判断文件夹是否存在, 不存在创建一个
    if (!fs.existsSync(path)) {
        fs.mkdirSync(path, { recursive: true })
    }
}

function setscript(opt) {
    const { formDirPath, toDirPath } = opt;
    const sourceFile = fs.readdirSync(formDirPath, { withFileTypes: true });

    sourceFile.forEach(file => {
        const newformDirPath = path.resolve(formDirPath, file.name)
        const newtoDirPath = toDirPath;
       
        if (file.isDirectory()) {
            setscript({
                formDirPath: newformDirPath,
                toDirPath: newtoDirPath,
            })
        } else {
            if (file.name.endsWith('.html')) { // 如果是.html文件
                var fileitem = fs.readFileSync(newformDirPath);
                var $ = cheerio.load(fileitem.toString());
                
                $('script').each((index, item) => {
                    const h = $(item).html().trim();
                    if (!!h) { // 页面写的js,抽离出来放到就是文件里面
                        const basename = path.basename(file.name, '.html');
                        isExist(path.resolve(newtoDirPath));
                        const r = `${Math.floor(Math.random() * 10000000000)}`
                        fs.writeFileSync(path.resolve(newtoDirPath, basename + r + '.js'), h); // 新增js文件
                        const pathjs = path.relative(newformDirPath, path.resolve(newtoDirPath, basename + r + '.js')).split(path.sep)
                        pathjs.splice(0,1)
                        $(item).html('').attr('src', pathjs.join("/"))
                    }
                    const jssrc = $(item).attr('src');
                    if (!!jssrc) {
                        if (jssrc.indexOf('http') == 0) { //cdn链接
                         // ...
                        } else { // 本地引用的文件
                         // ...
                        }
                    }
                })
                fs.writeFileSync(newformDirPath, $.html()); // 重新写入html,(删除了script)
            }
        }
    })
}


/*
// temp目录下的所有html文件里面的js,抽离出来放到 temp/tempjs文件夹下
setscript(
  {
    formDirPath: path.resolve(__dirname, 'temp'), // 
    toDirPath: path.resolve(__dirname, 'temp/tempjs'),
  }
)
*/
module.exports = setscript

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值