webpack学习第一期 去除空格

75 阅读1分钟

webpack 学习打卡 目的:去除空格 实际操作:将文件中空格去除存入新的文件中 writeFile('文件名','写入的内容',失败的回调)写入内容 写入文件不存在将自动创建文件 readFile('目标文件名',失败的和成功数据的回调)读取文件内容

// 引入fs
const fs = require('fs')
const path = require('path')

// 存入
const innStr = 'Hello _ _ Kitty'
fs.writeFile(path.join(__dirname, './filename.txt'), innStr, err => {
    if (err) console.log(err);
    else {
        console.log('成功在文件夹fliename中写入');
    }
})

// 清除空格 存入新文件
fs.readFile(path.join(__dirname, './filename.txt'), (err, data) => {
    if (err) console.log(err);
    else {
    //使用正则表达式替换空格
        const resStr = data.toString().replace(/[' ']/g, '')
        // console.log(resStr);
        fs.writeFile(path.join(__dirname, './newFilename.txt'), resStr, err => {
            if (err) console.log(err);
            else {
                console.log('成功在新文件newFliename中写入');
                fs.readFile(path.join(__dirname, './newFilename.txt'), (err, data) => {
                    if (err) console.log(err);
                    else {
                        console.log('成功去除空格', data.toString());
                    }
                })
            }
        })
    }
})