从Windows命令提示符运行JavaScript [英] Running JavaScript from the windows command prompt

查看:101
本文介绍了从Windows命令提示符运行JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下JavaScipt代码,将二进制数字转换为十进制数字:

I wrote the following JavaScipt code which converts a binary number into a decimal number:

(function bin_dec(num) {
  var x = num;
  var result = 0;
  for (var i = 0; i < x.length; i++) {
    result += eval(x[x.length - i] * 2^i);
  }
  return result;
})()

我希望能够从命令行运行此代码。文件名是 converter.js ,并且我在与文件相同的目录中运行命令提示符窗口。我正在尝试使用 01001100 作为函数参数来运行此代码。这是我的尝试:

I want to be able to run this code from the command-line. The filename is converter.js and I am running the command prompt window in the same directory as the file. I am trying to run this code using 01001100 as the function argument. Here are my attempts:

$ converter.js 01001100

$ converter.js -01001100

$ converter.js bin_dec(01001100)

但是不幸的是,这两种方法都不起作用。有人可以指出我的错误吗?

But unfortunately, neither of these works. Can somebody please point out my mistake? Thanks in advance.

推荐答案

1)安装 Node.js (如果尚未这样做)。

1) Install Node.js if you haven't done so yet.

2)更改您的 converter.js 文件如下:

2) Change your converter.js file like this:

function bin_dec(num) {
  return parseInt(num, 2);
}

console.log(bin_dec(process.argv[2]));

3)在脚本所在的文件夹中打开一个新命令提示符,然后运行

3) Open a new command prompt in the folder where your script is and run

$ node converter.js 01001100

这篇关于从Windows命令提示符运行JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆