nodejs模块学习
目录
一、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>