gpt4 book ai didi

node.js - 如何将命令从 BAT 文件发送到在 Windows 中运行的 NodeJS 进程?

转载 作者:可可西里 更新时间:2023-11-01 09:37:00 30 4
gpt4 key购买 nike

在通过批处理文件运行 nodejs 服务器时是否可以在批处理文件中制作/使用自定义文本命令?

//Current batch file
node nodeServer.js

//nodeServer.js
function list(){
//insert query
}
function unlist(){
//delete query
}

截至目前,在我启动批处理文件后,nodeServer.js 已启动并且批处理停止接受任何输入。

我希望能够键入“nodeServer.js list”(在批处理窗口中),然后调用 nodeServer.js 中名为“list”的函数,

我希望通过使用“list”函数运行插入查询将有关服务器的数据插入数据库,并使用 nodeServer.js unlist 运行删除查询以在再次关闭服务器之前删除插入的行。

我不熟悉批处理文件,这可能吗?

更新

澄清..我想在批处理窗口中键入一个文本命令,在它启动 nodejs 服务器之后,运行在 nodeServer.js 中找到的特定功能

最佳答案

您想在 Node 进程启动后向 NodeJS 发送命令。

  • 要在不暂停 bat 文件的情况下从 NodeJS 启动命令,请使用 start
  • 为了发送命令,我将使用一个简单的文本文件。我将使用 echo 从批处理中写入文件,并使用 watchreadFileSync
  • 从 NodeJS 读取文件
  • 我将支持使用空格发送函数名称和参数。例如: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 文件名 = __目录名 + '/命令'

// 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)
}
}

阅读有关文件系统 Node 模块的更多信息:https://nodejs.org/docs/latest/api/fs.html#fs_class_fs_stats

关于node.js - 如何将命令从 BAT 文件发送到在 Windows 中运行的 NodeJS 进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677203/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com