对于一个一直用惯C++的人来说,突然转向nodejs开发是有些吃力的,首先要理解什么是nodejs,一看名字估计是和javascript相关的东西,其实它只是javascript的运行环境,采用的是Google V8引擎,运用事件驱动和异步iO的方式,是最近新起的一种技术。
公司的要求是实现一个前端和后端统一化的规格用nodejs做成rest,然后我做的这部分是实现c++的封装。安装什么的我就不在这里说了,google百度什么的都有。
首先在windows下可以直接采用安装包安装会自动配置,建立一个目录比如zskycode里面包含了这些内容
然后在binding.gyp里输入
{
'targets': [
{
'target_name': 'zskycode',
'sources': [
'src/hello.cc'
],
'conditions': [
['OS=="win"', {
'include_dirs': [
'deps/win32/include'
],
'libraries': [
# TODO: fix node-gyp behavior that requires ../
# '../deps/win32/lib'
]
}]
]
}
]
}
配置源文件 库和包含目录
建立package.json
{
"name": "zskycode",
"version": "0.0.4",
"author": "ZSkycode <zzg.script@gmail.com>",
"description": "Sample package for Node.js",
"repository": {
"type": "git",
"url": ""
},
"homepage": "",
"main": "./lib/index.js",
"keywords": [
],
"engines": {
"node": ">=0.6.14"
},
"dependencies": {
},
"scripts": {
"install": "node-gyp rebuild"
},
"devDependencies": {},
"optionalDependencies": {}
}
也可以用npm init方式进行对话式的输入这些信息
在lib文件夹里建立binding.gyp中提到的src文件hello.cc
/*
* create by Zork-zzg 2014/4/2
*/
#define BUILDING_NODE_EXTENSION
include <node.h>
#include <v8.h>
using namespace v8;
Handle<Value> Method(const Arguments& args)
{
HandleScope scope;
return scope.Close(String::New("hello,world"));
}
void init(Handle<Object> exports)
{
exports->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Method)->GetFunction());
}
NODE_MODULE(zskycode, init)
然后用命令行转到zskycode文件夹目录下,输入npm-gyp configure 如果没有错误继续执行npm-gyp build就会在release目录下生成你想要的node文件
然后
var hello = require('./build/Release/hello.node').hello();
console.log(hello); //这里打印world字符串
其实只要你把工程建立在node_modules文件夹下的话可以直接
var hello = require('zskycode.hello();
console.log(hello); //这里打印world字符串
它会执行package.json文件里的main方法调用index.js
var addon = require(__dirname + '/../build/Release/zskycode.node');
module.exports = addon;
当然这个例子只是简单的helloworld 你也可以发布它 npm adduser创建账号然后npm publish发布
然后其他人就可以通过npm install zskycode下载了
这一篇就说到这里。