Iawen's Blog

我喜欢这样自由的随手涂鸦,因为我喜欢风......

1. hello,world 入门

1.1 代码

#include <node.h>
#include <v8.h>

namespace hello{
	using v8::Exception;
	using v8::FunctionCallbackInfo;
	using v8::Isolate;
	using v8::Local;
	using v8::String;
	using v8::Value;
	using v8::Object;

	void SayHello(const FunctionCallbackInfo<Value>& args){
        Isolate* isolate = args.GetIsolate();
        args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World!"));
	}

	void Init(Local<Object> exports){
        NODE_SET_METHOD(exports, "sayHello", SayHello);
	}

	NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
}

配置gyp文件(文件名必需是:binding.gyp)

{
	'targets': [
		{
			'target_name': 'hello',
			'sources': [
				'hello.cc'
			]
		}
	],
}​

2.1 编译步骤

[root@iawen hello]# node-gyp configure build
gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.2
gyp info using node@10.0.0 | linux | x64
gyp info spawn /usr/bin/python2
gyp info spawn args [ '/usr/local/lib/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'make',
gyp info spawn args '-I',
gyp info spawn args '/home/learn/nodejs/hello/build/config.gypi',
gyp info spawn args '-I',
gyp info spawn args '/usr/local/lib/node_modules/node-gyp/addon.gypi',
gyp info spawn args '-I',
gyp info spawn args '/root/.node-gyp/10.0.0/include/node/common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=/root/.node-gyp/10.0.0',
gyp info spawn args '-Dnode_gyp_dir=/usr/local/lib/node_modules/node-gyp',
gyp info spawn args '-Dnode_lib_file=/root/.node-gyp/10.0.0/<(target_arch)/node.lib',
gyp info spawn args '-Dmodule_root_dir=/home/learn/nodejs/hello',
gyp info spawn args '-Dnode_engine=v8',
gyp info spawn args '--depth=.',
gyp info spawn args '--no-parallel',
gyp info spawn args '--generator-output',
gyp info spawn args 'build',
gyp info spawn args '-Goutput_dir=.' ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
make: 进入目录“/home/learn/nodejs/hello/build”
 CXX(target) Release/obj.target/hello/hello.o
 SOLINK_MODULE(target) Release/obj.target/hello.node
 COPY Release/hello.node
make: 离开目录“/home/learn/nodejs/hello/build”
gyp info ok

1.3 调用

[root@iawen hello]# node
> var hello = require('./build/Release/hello.node');
> console.log(hello.sayHello());
Hello World!