devilfish-dbms
Version:
a database that based on key-value map and is successful in deal with saved in disk and high-performance in select that act as a memory-based database
114 lines (98 loc) • 3.23 kB
JavaScript
const worker = require('worker_threads');
const express = require('express');
const { spawn, exec } = require('child_process');
const app = express();
const port = 3125;
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
exec('dir',{encoding: 'utf8'},(error,stdout,stderr)=>{
if(error){
console.log(`error:${error.message}`);
return;
}
if(stderr){
console.log(`stderr:${stderr}`);
return;
}
console.log(`stdout:${stdout}`);
});
// 处理POST请求并执行命令
app.post('/execute', (req, res) => {
console.log(req.body);
console.log(__dirname);
try {
console.log('Received request:', req.body);
// 验证请求体是否为有效的JSON
if (!req.body || typeof req.body !== 'object') {
return res.status(400).json({error: 'Invalid request body'});
}
const { command } = req.body;
if (!command) {
return res.status(400).json({error: 'Command is required'});
}
console.log('Received command:', command);
console.log(req.body);
// 使用spawn启动main_database.js
// 全局变量保存子进程实例
let childProcess;
// 初始化子进程
function initChildProcess() {
if (!childProcess) {
childProcess = spawn('node', ['./main_database.js'], {
cwd: __dirname,
stdio: ['pipe', 'pipe', 'pipe']
});
// 错误处理
childProcess.on('error', (err) => {
console.error('Child process error:', err);
childProcess = null;
});
// 进程退出处理
childProcess.on('exit', (code) => {
console.log(`Child process exited with code ${code}`);
childProcess = null;
});
}
return childProcess;
}
// 在请求处理中使用
const process = initChildProcess();
let output = '';
// 实时收集输出
let responseSent = false;
process.stdout.on('data', (data) => {
output += data.toString();
// 当检测到完整响应时返回结果
if (output.includes('\n') && !responseSent) {
res.status(200).json({result: output.trim()});
output = '';
responseSent = true;
}
});
process.stderr.on('data', (data) => {
console.error('Child process stderr:', data.toString());
if (!responseSent) {
res.status(500).json({error: data.toString()});
responseSent = true;
}
});
// 发送命令
process.stdin.write(command + '\n');
// 设置超时返回部分结果
setTimeout(() => {
if (!responseSent) {
res.status(200).json({result: output || 'No response from database process'});
output = '';
responseSent = true;
}
}, 1000);
} catch (err) {
console.error('Error processing request:', err);
res.status(500).json({error: 'Internal server error'});
}
});
// 启动服务器
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});