C语言 scanf/sscanf 的 node.js 实现模块 node-scanf
发布于 9 年前 作者 lellansin 7411 次浏览 最后一次编辑是 8 年前 来自 分享

node-scanf NPM Version Build Status Coveralls Status

使用 node.js 编写 shell 脚本的时候,你可能想要一个简单的、同步的、像C语言中的scanf一样有格式的获取输入的函数,该模块能帮到你。 另外,当你要读取某些特定格式的数据(例如 ps 命令出来的进程数据、csv 文件或者自定义格式的数据)的时候该模块的 sscanf 也能帮到你。

Github: https://github.com/Lellansin/node-scanf

安装

npm install scanf --save

目前支持的格式

  • %d - 整数
  • %f - 浮点数
  • %s - 字符串
  • %S - 字符串(匹配处开始往后一整行)
  • %x - 十六进制数字
  • %o - 八进制数字

例子

Quickly start

var scanf = require('scanf');

console.log('请输入你的名字');
var name = scanf('%s');

console.log('请输入你的年纪');
var age = scanf('%d');

console.log('名字 [%s] 类型: [%s]', name, typeof name);
console.log('年纪 [%s] 类型: [%s]', age, typeof age);

输出

请输入你的名字
> Barack\ Obama
请输入你的年纪
> 24
名字 [Barack Obama] 类型: [string]
年纪 [24] 类型: [number]

类 C语言格式

var scanf = require('scanf');

console.log('你的生日是? \(年-月-日\)');
var date = scanf('%d-%d-%d');

console.log('你的生日 [%s]', date);

输出

你的生日是? (年-月-日)
> 1990-01-01
你的生日 [1990,1,1]

返回方式

直接返回

var scanf = require('scanf');

var number = scanf('%d');

console.log('number', number);

输出

>> 2015    
number 2015

Array 返回

var scanf = require('scanf');

var result = scanf('%s%d%d');

console.log('result', result);

输出

>> Alan 24 180        
result [ 'Alan', 24, 180 ]

Json 返回

var scanf = require('scanf');

var result = scanf('%d %f %s %x %o', 'integer', 'float', 'string', 'hex', 'octal');

console.log('result', result);

输出

>> 12 3.1415926 hello 1F 10    
result { 
  integer: 12,
  float: 3.1415926,
  string: 'hello',
  hex: 31,
  octal: 8 
}

sscanf

REPL

>> var sscanf = require('scanf').sscanf;
undefined
>> sscanf('12 34', '%d');
12
>> sscanf('Alan 20 180', '%s%d%d')
[ 'Alan', 20, 180 ]
>> sscanf('12 3.1415926 hello', '%d %f %s', 'month', 'pi', 'world');
{ month: 12, pi: 3.1415926, world: 'hello' }
>> sscanf('   14   ??  Ss     0:07.59 /usr/sbin/securityd -i', '%d %s %s %s %s %s', 'pid', 'tty', 'stat', 'time', 'exec', 'param');
{ pid: 14,
  tty: '??',
  stat: 'Ss',
  time: '0:07.59',
  exec: '/usr/sbin/securityd',
  param: '-i' }

更多详细可以见 ./tests 中的单元测试。

如果有格式不支持或者报错可以在 issues 上留言,或者邮件联系作者 lellansin@gmail.com

2 回复

昨天 npm 上下载量破了 2k(平常下载量20不到),心情好好,所以挖坟顶上来 [doge]

回到顶部