Nodejs 杂记
最近被赶鸭子上架,强行要求写个nodejs接口,作为一名来JavaScript都不的选手,一脸懵逼。语法障碍已成为第一大障碍,把这两天用到的函数,记录一下省的下次还得再百度。
主要包含以下几个方面:
- 如何去除字符串中最后面的空格
- 如何去除字符串中的双引号
- nodejs中JSON字符串与对象转换
- 如何合并buffer
1. 删除字符串中最后面的空格
通过使用trim()
函数可以实现去除字符串最后的空格,语法与JavaScript中相同。
customerid = customerid.toString().trim();//去掉编号后面的空格
2. 去除字符串中所有的双引号
通过使用replace()
方法,第一个参数代表要取代的内容,第二个参数代表替换为什么。
sendData = sendData.replace(/\"/g, "");//去掉所有的双引号
3. nodejs中JSON字符串与对象转换
3.1 将JSON对象转换为JSON类型的字符串。
使用JSON.stringify()
可以将JSON对象转换为JSON类型的字符串。
result = {};
var length = parseInt(data.substring(pos, pos+4));//获取交易长度
result.length = length;
pos += 4;
var dealtype = data.substring(pos, pos+4);//获取交易类型
result.dealtype = dealtype;
pos += 4;
var getjson = JSON.stringify(result);
3.2 将JSON类型的字符串转换为JSON对象
使用JSON.parse()
,可以将JSON类型的字符串转换为JSON对象。
result = {};
var length = parseInt(data.substring(pos, pos+4));//获取交易长度
result.length = length;
pos += 4;
var dealtype = data.substring(pos, pos+4);//获取交易类型
result.dealtype = dealtype;
pos += 4;
var getjson = JSON.stringify(result);
var getjsonstring = JSON.parse(getjson);
4. 合并buffer
nodejs官方文档中提供了方法Buffer.concat(list[, totalLength])
1. list 要合并的 Buffer 或 Uint8Array 实例的数组
2. totalLength 合并时 list 中 Buffer 实例的总长度
3. 返回: <Buffer>
返回一个合并了 list 中所有 Buffer 实例的新建的 Buffer 。
如果 list 中没有元素、或 totalLength 为 0 ,则返回一个新建的长度为 0 的 Buffer 。
如果没有提供 totalLength ,则从 list 中的 Buffer 实例计算得到。 为了计算 totalLength 会导致需要执行额外的循环,所以提供明确的长度会运行更快。
如果提供了 totalLength,totalLength 必须是一个正整数。如果从 list 中计算得到的 Buffer 长度超过了 totalLength,则合并的结果将会被截断为 totalLength 的长度。
const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;
// 输出: 42
console.log(totalLength);
const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
// 输出: <Buffer 00 00 00 00 ...>
console.log(bufA);
// 输出: 42
console.log(bufA.length);
5.0小记
Nodejs还是非常强大的一种编程语言,语法跟JavaScript很像,而且功能强大,好多东西都不用自己手写,很方便,初步接触印象良好。