GVKun编程网logo

Node.js如何执行cmd(nodejs如何执行cmd指令)

23

最近很多小伙伴都在问Node.js如何执行cmd和nodejs如何执行cmd指令这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展C++执行CMD命令、C#执行cmd命令、C#中执行

最近很多小伙伴都在问Node.js如何执行cmdnodejs如何执行cmd指令这两个问题,那么本篇文章就来给大家详细解答一下,同时本文还将给你拓展C ++执行CMD命令、C# 执行cmd命令、C#中执行cmd命令、C#隐式执行CMD命令等相关知识,下面开始了哦!

本文目录一览:

Node.js如何执行cmd(nodejs如何执行cmd指令)

Node.js如何执行cmd(nodejs如何执行cmd指令)

最近正好因业务的一个需求需要研究如何根据vscode的插件名来下载对应的插件以解决之前将插件打包上传到服务器上面导致的延迟问题(插件体积小还好说,如果体积过大,即便是压缩打成zip包,如果同一时刻很多人上传或下载,系统延迟将会非常严重)。
之前一直想不明白,找半天找不到要给URL可以下载,最后不经意间有了灵感转变一下思路搞定了。灵感是一个好东西。
本文主要讲Node.js如何执行cmd,应用场景除了我开头说的,其实还有很多,只有想不到,没有做不到。正如我们经理说的,现在基本上20%的技术可以解决80%的业务问题,这个时代,技术有点泛滥,换言之,技术产能过剩。

一、下载node-cmd

npm install -g node-cmd

二、编写测试函数(index.js)

var nodeCmd = require(''node-cmd'');
 
function runCmdTest() {

               var fileName = "ms-ceintl.vscode-language-pack-zh-hans";

               console.log("fileNames:"+fileName);
               
               nodeCmd.get(
             
                    ''code --install-extension ''+fileName+'' --extensions-dir="D:\1024Workspace\extension"'',
             
                    function(err, data, stderr){
             
                        console.log(data);
             
                    }
             
                );

        nodeCmd.run(''code --install-extension ''+fileName+'' --extensions-dir="D:\1024Workspace\extension"'');

}

console.log(runCmdTest());

参考资料如下:
nodejs 运行CMD命令

C ++执行CMD命令

C ++执行CMD命令

我在这里有一个严重的问题。 我需要通过C ++执行CMD命令行,而不显示控制台窗口。 所以我不能使用system(cmd) ,因为窗口会显示。

我已经尝试winExec(cmd,SW_HIDE) ,但这也不起作用。 CreateProcess是我尝试的另一个。 但是,这是用于运行程序或batch file。

我已经结束了尝试ShellExecute :

ShellExecute( NULL,"open","cmd.exe","ipconfig > myfile.txt","c:projectsb",SW_SHOWnorMAL );

任何人都可以看到上面的代码有什么问题吗? 我已经使用SW_SHOWnorMAL直到我知道这个工程。

虚拟键盘自定义

_beginthread与CreateThread

在Linux内核模块中调用用户空间函数

如何告诉MinGW链接器不要导出所有符号?

基本的unit testing和C,我怎么开始?

我真的需要一些帮助。 没有任何东西显露出来,我一直在尝试一段时间。 任何人可以给的build议将是伟大的:)

读取audiostream到输出设备

可执行C程序中的段

使用PyTimeChart了解和调整Linux调度程序

如何判断一个Linux TTY是否正在控制一个进程组

如何杀死一个PID不断变化的进程?

将输出重定向到你自己的管道是一个更整洁的解决方案,因为它避免了创建输出文件,但是这个工作正常:

ShellExecute(0,"/C ipconfig > out.txt",SW_HIDE);

您没有看到cmd窗口,并且输出按预期重定向。

您的代码可能会失败(除了/C之外),因为您将路径指定为"c:projectsb"而不是"c:\projects\b" 。

您应该使用cmd.exe上的CreateProcess和/C参数来隧道ipconfig命令。 >本身在命令行上不起作用。 您必须以编程方式重定向stdout 。

这里是我的DosExec函数的实现,它允许(静默)执行任何DOS命令,并以unicode字符串的形式检索生成的输出。

// Convert an OEM string (8-bit) to a UTF-16 string (16-bit) #define OEMtoUNICODE(str) CHARtoWCHAR(str,CP_OEMCP) /* Convert a single/multi-byte string to a UTF-16 string (16-bit). We take advantage of the MultiBytetoWideChar function that allows to specify the charset of the input string. */ LPWSTR CHARtoWCHAR(LPSTR str,UINT codePage) { size_t len = strlen(str) + 1; int size_needed = MultiBytetoWideChar(codePage,str,len,NULL,0); LPWSTR wstr = (LPWSTR) LocalAlloc(LPTR,sizeof(WCHAR) * size_needed); MultiBytetoWideChar(codePage,wstr,size_needed); return wstr; } /* Execute a DOS command. If the function succeeds,the return value is a non-NULL pointer to the output of the invoked command. Command will produce a 8-bit characters stream using OEM code-page. As charset depends on OS config (ex: CP437 [OEM-US/latin-US],CP850 [OEM 850/latin-1]),before being returned,output is converted to a wide-char string with function OEMtoUNICODE. Resulting buffer is allocated with LocalAlloc. It is the caller's responsibility to free the memory used by the argument list when it is no longer needed. To free the memory,use a single call to LocalFree function. */ LPWSTR DosExec(LPWSTR command){ // Allocate 1Mo to store the output (final buffer will be sized to actual output) // If output exceeds that size,it will be truncated const SIZE_T RESULT_SIZE = sizeof(char)*1024*1024; char* output = (char*) LocalAlloc(LPTR,RESULT_SIZE); HANDLE readPipe,writePipe; Security_ATTRIBUTES security; STARTUPINFOA start; PROCESS_informatION processInfo; security.nLength = sizeof(Security_ATTRIBUTES); security.bInheritHandle = true; security.lpSecurityDescriptor = NULL; if ( CreatePipe( &readPipe,// address of variable for read handle &writePipe,// address of variable for write handle &security,// pointer to security attributes 0 // number of bytes reserved for pipe ) ){ GetStartupInfoA(&start); start.hStdOutput = writePipe; start.hStdError = writePipe; start.hStdInput = readPipe; start.dwFlags = STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW; start.wShowWindow = SW_HIDE; // We have to start the DOS app the same way cmd.exe does (using the current Win32 ANSI code-page). // So,we use the "ANSI" version of createProcess,to be able to pass a LPSTR (single/multi-byte character string) // instead of a LPWSTR (wide-character string) and we use the UNICODetoANSI function to convert the given command if (CreateProcessA(NULL,// pointer to name of executable module UNICODetoANSI(command),// pointer to command line string &security,// pointer to process security attributes &security,// pointer to thread security attributes TRUE,// handle inheritance flag norMAL_PRIORITY_CLASS,// creation flags NULL,// pointer to new environment block NULL,// pointer to current directory name &start,// pointer to STARTUPINFO &processInfo // pointer to PROCESS_informatION )){ // wait for the child process to start for(UINT state = WAIT_TIMEOUT; state == WAIT_TIMEOUT; state = WaitForSingleObject(processInfo.hProcess,100) ); DWORD bytesRead = 0,count = 0; const int BUFF_SIZE = 1024; char* buffer = (char*) malloc(sizeof(char)*BUFF_SIZE+1); strcpy(output,""); do { DWORD dwAvail = 0; if (!PeekNamedPipe(readPipe,&dwAvail,NULL)) { // error,the child process might have ended break; } if (!dwAvail) { // no data available in the pipe break; } ReadFile(readPipe,buffer,BUFF_SIZE,&bytesRead,NULL); buffer[bytesRead] = ''; if((count+bytesRead) > RESULT_SIZE) break; strcat(output,buffer); count += bytesRead; } while (bytesRead >= BUFF_SIZE); free(buffer); } } CloseHandle(processInfo.hThread); CloseHandle(processInfo.hProcess); CloseHandle(writePipe); CloseHandle(readPipe); // convert result buffer to a wide-character string LPWSTR result = OEMtoUNICODE(output); LocalFree(output); return result; }

我有一个类似的程序(windows7和10测试)在github上

https://github.com/vlsireddy/remwin/tree/master/remwin

这是服务器程序

在windows的UDP端口(5555)上监听名为“Interface”的“Local Area Connection”并接收udp数据包。

接收到的udp数据包内容在cmd.exe上执行[运行命令后不要关闭cmd.exe,输出字符串[执行命令的输出]通过同一个udp端口反馈给客户端程序]。

换句话说,在udp数据包中接收到的命令 – >解析的udp数据包 – >在cmd.exe – >输出上执行的输出在同一端口上发送回客户端程序

这不显示“控制台窗口”没有人需要执行cmd.exe手动命令remwin.exe可以在后台运行,其瘦服务器程序

C# 执行cmd命令

C# 执行cmd命令

代码:

/// <summary>
        /// 执行cmd命令
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <returns></returns>
        private static string ExeCmd(string cmd)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process()
            {
                StartInfo = {
                      FileName = "cmd.exe",
                UseShellExecute = false,    //是否使用操作系统shell启动
                RedirectStandardInput = true,//接受来自调用程序的输入信息
                RedirectStandardOutput = true,//由调用程序获取输出信息
                RedirectStandardError = true,//重定向标准错误输出
                CreateNoWindow = true,//不显示程序窗口
                }

            };
            p.Start();//启动程序

            //向cmd窗口发送输入信息            
            cmd = string.IsNullOrEmpty(cmd) ? "exit" : $"{cmd}&exit";
            p.StandardInput.WriteLine(cmd);
            p.StandardInput.AutoFlush = true;
            //p.StandardInput.WriteLine("exit");
            //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
            //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令

            //获取cmd窗口的输出信息
            return p.StandardOutput.ReadToEnd();
        }

  

C#中执行cmd命令

C#中执行cmd命令

  • proxy等set、环境变量信息共享操作系统的CMD的配置
  • 注意异常处理、进程的回收
  • 下面实现的缺点是,返回的字符串中有冗余数据,如打开CMD时的运行环境信息,因此可能要自己再去过滤出来哪些才是命令返回的数据
  • 不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
    /// <summary>
    /// 
    /// </summary>
    public class Cmd
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmd"></param>
        public static string RunCmd(string cmd)
        {
            using (Process proc = new Process())
            {
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.Start();
                proc.StandardInput.WriteLine(cmd);
                proc.StandardInput.WriteLine("exit");
                string outStr = proc.StandardOutput.ReadToEnd();
                proc.Close();
                return outStr;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="programName"></param>
        /// <param name="cmd"></param>
        public static void RunProgram(string programName, string cmd)
        {
            using (Process proc = new Process())
            {
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.FileName = programName;
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.Start();
                if (cmd.Length != 0)
                {
                    proc.StandardInput.WriteLine(cmd);
                }
                proc.Close();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="programName"></param>
        public static void RunProgram(string programName)
        {
            RunProgram(programName, "");
        }
    }

C#隐式执行CMD命令

C#隐式执行CMD命令

在命令文本框输入DOS命令,点击“Run”按钮,在下面的文本框中输出运行结果。
在这里插入图片描述
下面是实现代码

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using WindowsFormsApplication2;
 
  
namespace RunDosCommandForm
{
   
  public partial class Form1 : Form
  {
   
    public Form1()
    {
   
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
   
    	//文本框内容(输入的命令进行传参)
        ExcuteDosCommand(textBox1.Text);
    }

    private void ExcuteDosCommand(string cmd)
    {
   
      try
      {
   
        Process p = new Process();
        p.StartInfo.FileName = "cmd";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.CreateNoWindow = true;
        p.OutputDataReceived += new DataReceivedEventHandler(sortProcess_OutputDataReceived);
        p.Start();
        StreamWriter cmdWriter = p.StandardInput;
        p.BeginOutputReadLine();
        if (!String.IsNullOrEmpty(cmd))
        {
   
          cmdWriter.WriteLine(cmd);
        }
        cmdWriter.Close();
        p.WaitForExit();
        p.Close(); 
      }
      catch(Exception e)
      {
   
        MessageBox.Show("执行命令失败,请检查输入的命令是否正确!");
      }
    }
  
    private void sortProcess_OutputDataReceived(object sender,DataReceivedEventArgs e)
    {
   
      if(!String.IsNullOrEmpty(e.Data))
      {
   
        this.BeginInvoke(new Action(() => {
    this.listBox1.Items.Add(e.Data);}));         
      }
    }
	//窗口加载时执行
    private void Form1_Load(object sender, EventArgs e)
    {
   
        ExcuteDosCommand(textBox1.Text);
    }

    
  }
}

今天的关于Node.js如何执行cmdnodejs如何执行cmd指令的分享已经结束,谢谢您的关注,如果想了解更多关于C ++执行CMD命令、C# 执行cmd命令、C#中执行cmd命令、C#隐式执行CMD命令的相关知识,请在本站进行查询。

本文标签: