2011
Dec
30
javascript 没有档案存取的功能,今天就写了两个 js extension,分别实现同 php的 file_get_contents() 与 file_put_contents ,这两个档案处理的function 。
file_get_contents
这里用简单的 c++语法实现读取档案
- Handle<Value> file_get_contents(const Arguments& args){
- String::Utf8Value ag(args[0]);
- string file = string(*ag);
- string response="";
- ifstream f;
- f.open(file.c_str(), ios::in | ios::binary);
- if( f.fail() ){
- }
- else{
- while(!f.eof()){
- f >> response;
- }
- }
- f.close();
- return String::New(response.c_str());
- }
file_put_contents
这里用简单的 c++语法实现写入档案
- Handle<Value> file_put_contents(const Arguments& args){
- if( args.Length()!=2 ){
- cerr << "Arguments : path , data";
- return Boolean::New(false);
- }
- String::Utf8Value ag(args[0]);
- String::Utf8Value d(args[1]);
- string path = string(*ag);
- string data = string(*d);
- ofstream f;
- f.open(path.c_str(), ios::out | ios::binary);
- if(f.is_open()){
- f << data ;
- f.close();
- }
- else{
- cerr << "Can not open file "<< path;
- return Boolean::New(false);
- }
- return Boolean::New(true);
- }
create Template
将 file_get_contents 与 file_put_contents 绑进 ObjectTemplate
- Handle<ObjectTemplate> createBasicTemplate(){
- Local<ObjectTemplate> t = ObjectTemplate::New();
- t->Set("file_get_contents",FunctionTemplate::New(file_get_contents));
- t->Set("file_put_contents",FunctionTemplate::New(file_put_contents));
- return t;
- }
file handle main test
- #include <v8.h>
- #include <string.h>
- #include <iostream>
- #include <fstream>
- using namespace std;
- using namespace v8
- v8::Handle<v8::String> ReadFile(const char* name);
- int main (){
- Handle<ObjectTemplate> global;
- HandleScope handle_scope;
- Handle<Context> context;
- global = createBasicTemplate();
- context= Context::New(NULL,global);
- Context::Scope context_scope(context);
- Handle<v8::String> source = ReadFile("file.js");
- Handle<Script> script = Script::Compile(source);
- Handle<Value> result = script->Run();
- // context.Dispose();
- String::Utf8Value str(result);
- script = Script::Compile(String::New("result"));
- result = script->Run();
- cout << *String::Utf8Value(result);
- return 0;
- }
js 语法测试
- file_put_contents('t.txt',"测试写入档案");
- var result=file_get_contents('t.txt');