通过它运行nodejs服务器时,是否可以在批处理文件中创建/使用自定义文本命令?
//Current batch file
node nodeServer.js
//nodeServer.js
function list(){
//insert query
}
function unlist(){
//delete query
}
截至目前,我启动批处理文件后,启动了nodeServer.js,批处理停止接受任何输入。
我希望能够键入" nodeServer.js list"(在批处理窗口中),然后调用一个名为" list"的函数。在nodeServer.js中,
我希望通过使用" list"运行插入查询来将有关服务器的数据插入到数据库中。函数并运行带有nodeServer.js的删除查询unlist,以便在再次关闭服务器之前删除插入的行。
我不熟悉批处理文件,这可能吗?
更新
澄清...... 我想在批处理窗口中输入一个文本命令,在它启动了nodejs服务器之后,运行在nodeServer.js中找到的特定函数
答案 0 :(得分:0)
您希望在节点进程启动后向NodeJS发送命令。
start
echo
从批处理中写入文件,并使用watch
和readFileSync
list a b c
BAT文件:
@echo off This is make the bat file to not show the commands
REM `Rem` do nothing. It is exactly like // in javascript
REM This will start NodeJS without pause the bat
start node myNode.js
REM delete the command file if it exists
del command
REM Send 3 commands to the file. You can also add parameters
echo list >> command
echo list a b c>> command
echo unlist>> command
var fs = require(' fs') var filename = __dirname +' / command'
// Add here any command you want to be run by the BAT file
var commands = {
list: function() {
console.log('list', arguments)
},
unlist: function() {
console.log('unlist', arguments)
}
}
console.log('watching:' + filename)
if (fs.existsSync(filename)) {
console.log('File exists, running initial command')
runCommand()
}
require('fs').watchFile(filename, runCommand)
function runCommand() {
if(!fs.existsSync(filename)) return
var lines = fs.readFileSync(filename, 'utf-8').split('\r\n')
console.log(lines)
fs.unlink(filename)
for(var i=0;i<lines.length;i++){
var line=lines[i]
console.log(line)
line=line.split(' ') // Split to command and arguments
var command = line[0]
var args = line.slice(1)
if (!commands[command]) {
console.log('Command not found:"' + command +'"')
return;
}
console.log('Running command:', command, '(', args, ')')
commands[command].call(null, args)
}
}
阅读有关FileSystem节点模块的更多信息:https://nodejs.org/docs/latest/api/fs.html#fs_class_fs_stats