nodejs模块学习

nodejs模块学习

目录

nodejs模块学习

一、child_process模块

spawn使用

二、fs模块


一、child_process模块

spawn使用

官网示例代码

const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`输出:${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`错误:${data}`);
});

ls.on('close', (code) => {
  console.log(`子进程退出码:${code}`);
});

spawnSync 或者spawn  返回都为为buffer 解决方案

ls.stdout.toString('ascii')

利用spawnSync获取当前代码远程地址

参考

const { spawnSync } = require('child_process');
const childProcessSync = async function (cmd, params, cwd, printLog = true) {
    return new Promise((resolve) => {
        const ls = spawnSync(cmd, params, {
            shell: true
        })
        printLog && console.info("ls", ls.stdout.toString('ascii'))

        resolve(ls.stdout.toString('ascii'))
    });
}
const getGitBranch = async function (cwd) {
    try {
        // const result = await childProcessSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], cwd, false);
        const result = await childProcessSync('git', ['remote', '-v'], cwd, false)
        console.info("result", result)
        if (!result.startsWith('fatal:')) {
            return result.split(' ')[0].split('\t')[1];
        }
    } catch (e) {
        return undefined;
    }
}

function getCdnFolderName = async function () {
    const branch = await getGitBranch(process.cwd());
 
}

文档参考

子进程 | Node.js 中文文档 | Node.js 中文网
javascript - child_process.spawn中奇怪的输出“<Buffer” - IT工具网

二、fs模块

readdirSync 获取指定目录的文件夹名字

fs.readdirSync("./")  ===》[ 'index.js', 'text.js' ]

statSync 该方法返回指定路径的Stats 类对象,Stats 类对象调用方法可获得信息 (fs.Stats 类)

 readFile异步阅读文件内容(第二个参数不指明为utf-8 默认为buffer)

fs.readFile(path.resolve('../public/index.html'), "utf-8", (error, stdout, stderr) => {
        console.info("error", error)
        console.info("stdout", stdout)
        console.info("stderr", stderr)
    })

readFileSync同步阅读文件内容 

  const res = fs.readFileSync(path.resolve('../public/index.html'), "utf-8");
  console.info("res", res)


  const buffer = fs.readFileSync(path.resolve('../public/index.html'));
  console.info("buffer", buffer)  ===》buffer <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 6c 61 6e 67 3d 22 7a 68 22 3e 0a 0a 3c 68 65 61 64 3e 0a 20 20 20 20 3c 6d 65 74 61 ... 2015 more bytes>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥肥呀呀呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值