美文网首页
nodejs File System

nodejs File System

作者: BULL_DEBUG | 来源:发表于2019-06-10 23:31 被阅读0次

得到文件与目录的信息:stat

const fs = require('fs');
fs.stat('index.js', (error, stats) => {
    if (error) {
        console.log(error)
    } else {
        console.log(stats)
        console.log(`文件:${stats.isFile()}`)
        console.log(`目录:${stats.isDirectory()}`)
    }
})

创建一个目录

const fs = require('fs');
fs.mkdir('logs', (error) => {
    if (error) {
        console.log(error)
    } else {
        console.log(`成功创建目录:logs`)
    }
})

创建文件并写入内容:writeFile,appendFile

const fs = require('fs');
fs.writeFile('logs/hello.log', 'hello ~ \n', (error) => {
    if (error) {
        console.log(error)
    } else {
        console.log(`成功写入文件`)
    }
})
fs.appendFile('logs/hello.log', '你好 ~ \n', (error) => {
    if (error) {
        console.log(error)
    } else {
        console.log(`成功写入文件`)
    }
})

读取文件内容:readFile

const fs = require('fs');
fs.readFile('logs/hello.log','utf8', (error, data) => {
    if (error) {
        console.log(error)
    } else {
        console.log(`读取成功:${data}`)
    }
})

列出目录的东西:readdir

const fs = require('fs');
fs.readdir('logs', (error, files) => {
    if (error) {
        console.log(error)
    } else {
        console.log(files)
    }
})

重命名目录或文件:rename

const fs = require('fs');
fs.rename('logs/hello.log', 'logs/greeting.log', (error) => {
    if (error) {
        console.log(error)
    } else {
        console.log('重命名成功')
    }
})

删除目录与文件:rmdir,unlink

const fs = require('fs');

fs.readdirSync('logs').map((file) => {
    fs.unlink(`logs/${file}`, (error) => {
        if (error) {
            console.log(error)
        } else {
            console.log(`成功删除文件:${file}`)
        }
    })
})
fs.rmdir('logs', (error) => {
    if (error) {
        console.log(error)
    } else {
        console.log('成功删除目录:logs')
    }
})

stream

const fs = require('fs');
const zlib = require('zlib')

// var fileReadStream = fs.createReadStream('data.json');
// var fileWriteStream = fs.createWriteStream('data-1.json')
// fileReadStream.pipe(fileWriteStream);

var fileReadStream = fs.createReadStream('data.json');
var fileWriteStream = fs.createWriteStream('data.json.gz')

fileWriteStream.on('pipe', (source) => {
    console.log(source)
})
fileReadStream
.pipe(zlib.createGzip())
.pipe(fileWriteStream);


// var count = 0;
// fileReadStream.once('data', (chunk) => {
//     console.log(chunk.toString())
// })

// fileReadStream.on('data', (chunk) => {
//     console.log(`${ ++count }接收到:${chunk.length}`)
//     fileWriteStream.write(chunk)
// })
// fileReadStream.on('end', () => {
//     console.log(`-- 结束 --`)
// })
// fileReadStream.on('error', (error) => {
//     console.log(error)
// })



相关文章

网友评论

      本文标题:nodejs File System

      本文链接:https://www.haomeiwen.com/subject/gkdxfctx.html