Node - Code Snippet Collect

node 环境变量

NODE_ENV=test node app

通过以上命令启动程序,指定当前环境变量 NODE_ENV 的值为 test,那么在 app.js 中可通过 process.env 来获取环境变量:

console.log(process.env.NODE_ENV) //test

Windows 用户需要首先设置环境变量,然后再执行程序:

set DEBUG=*
set NODE_ENV=test
node app

可以使用cross-env,解决window兼容问题

npm i cross-env -g
cross-env NODE_ENV=test node app

node退出process.exit说明

  • process.exit(0)表示成功完成,回调函数中,err将为null;
  • process.exit(非0)表示执行失败,回调函数中,err不为null,err.code就是我们传给exit的数字。

代码运行时间

  • 常规
var start = new Date();

setTimeout(function (argument) {
    // execution time simulated with setTimeout function
    var end = new Date() - start;
    console.info("Execution time: %dms", end);
}, 1000);

输出:

Execution time: 1002ms
  • node
var start = new Date();
var hrstart = process.hrtime();

setTimeout(function (argument) {
    // execution time simulated with setTimeout function
    var end = new Date() - start,
        hrend = process.hrtime(hrstart);

    console.info("Execution time: %dms", end);
    console.info("Execution time (hr): %ds %dms", hrend[0], hrend[1]/1000000);
}, 1);

输出:

Execution time: 1ms
Execution time (hr): 0s 1.025075ms

Execution time: 3ms
Execution time (hr): 0s 2.875302ms

From:How to Measure Execution Time in Node.js

Node逐行读取文件

  • 目前使用了假逐行读取:(项目s2json)
fs.readFileSync(item).toString().split('\n').forEach(function (line) {
    console.log(line);
})
  • readline库
  var readline = require('linebyline'),
      rl = readline('./somefile.txt');
  rl.on('line', function(line, lineCount, byteCount) {
    // do something with the line of text 
  })
  .on('error', function(e) {
    // something went wrong 
  });

Read lines synchronously from file in Node.js
Node.js read and write file lines

node输出json文件且格式规范foramt

一般直接写入的json会输出一行,实际可通过JSON.stringify的参数设置。
具体输出json,参照此方案write/add data in JSON file using node.js,输出规范见下:

var fs = require('fs');

fs.writeFile('test.json', JSON.stringify({ a:1, b:2, c:3 }, null, 4));
/* test.json:
{
     "a": 1,
     "b": 2,
     "c": 3,
}
*/

How can I pretty-print JSON using node.js?

node - log打印记录在专有文件中

node常见的console记录,如需要备份到本地文件目录,方便查看,可以简单写一个方法。目前使用在云平台安装盘后台node服务中:

var fs = require('fs');
var util = require('util');
var path = require('path');

var error_path = path.join(process.cwd(), 'error.log');
var debug_path = path.join(process.cwd(), 'debug.log');
var error_file = fs.createWriteStream(error_path, {flags : 'w'});
var debug_file = fs.createWriteStream(debug_path, {flags : 'a'});
var log_stdout = process.stdout;

var log = {};

log.error = function(d) { //
  error_file.write(util.format(d) + '\n');
  log_stdout.write(util.format(d) + '\n');
};

log.debug = function(d) {
  debug_file.write(util.format(d) + '\n');
  log_stdout.write(util.format(d) + '\n');
}

module.exports = log;

可以使用log.error(),log.debug()

Node: log in a file instead of the console

大小写转换

遇到首字母需要大写,思路是将字符串split成数组,再将收字母大写。
遂用到这个思路:

单个字符转数字: 
'a'.charCodeAt(0) 
'A'.charCodeAt(0)
结果: 97 65
再将数字转为字母: 
String.fromCharCode(97) 

node逐行读取写入

ncbuild插件时用到,拷贝替换用到了readlinestream:

# 创建流
    var fRead = fs.createReadStream(item);
    var fWrite = fs.createWriteStream(dest);

# 单行读取
    var rl = readline.createInterface({
      input: fRead,
      terminal: true
    });

# API,回调方法写入
    rl.on('line', (line) => {
      var newLine = line
        .replace(REPLACE.name, OUT.name)
        .replace(REPLACE.type, OUT.type)
        .replace(REPLACE.node, OUT.node)
        .replace(REPLACE.upperName, OUT.upperName)
        + os.EOL;
      fWrite.write(newLine);
    });

# API,关闭回调
    rl.on('close', () => {
      // console.log(item,'...close')
    })

element(DOM)元素绑定自定义事件并执行

so地址

  • 定义 ``` function Event(name){ this.name = name; this.callbacks = []; } Event.prototype.registerCallback = function(callback){ this.callbacks.push(callback); }

function Reactor(){
this.events = {};
}

Reactor.prototype.registerEvent = function(eventName){
var event = new Event(eventName);
this.events[eventName] = event;
};

Reactor.prototype.dispatchEvent = function(eventName, eventArgs){
this.events[eventName].callbacks.forEach(function(callback){
callback(eventArgs);
});
};

Reactor.prototype.addEventListener = function(eventName, callback){
this.events[eventName].registerCallback(callback);
};

* 实例化执行:

var reactor = new Reactor();

reactor.registerEvent('big bang');

reactor.addEventListener('big bang', function(){
console.log('This is big bang listener yo!');
});

reactor.addEventListener('big bang', function(){
console.log('This is another big bang listener yo!');
});

reactor.dispatchEvent('big bang');

* 输出结果

This is big bang listener yo!
This is another big bang listener yo!

#### node命令行工具输入值

npm install --save co co-prompt

使用:
  • var co = require('co');
  • var prompt = require('co-prompt'); var program = require('commander'); ... .option('-u, --username ', 'The user to authenticate as') .option('-p, --password ', 'The user\'s password') .action(function(file) {
  • co(function *() {
  • var username = yield prompt('username: ');
  •  var password = yield prompt.password('password: ');

    console.log('user: %s pass: %s file: %s',

  •      program.username, program.password, file);
  •      username, password, file);
  • });
    })
    ...

    结果:

    $ snippet my_awesome_file
    username: kannonboy
    password: *************************
    user: kannonboy pass: correcthorsebatterystaple file: my_awesome_file

node路径说明

  • __dirname: 总是返回被执行的 js 所在文件夹的绝对路径
  • __filename: 总是返回被执行的 js 的绝对路径
  • process.cwd(): 总是返回运行 node 命令时所在的文件夹的绝对路径
@2017-05-16 15:02