2011
Dec
30




javascript 没有档案存取的功能,今天就写了两个 js extension,分别实现同 php的 file_get_contents() 与 file_put_contents ,这两个档案处理的function 。

file_get_contents

这里用简单的 c++语法实现读取档案

  1. Handle<Value> file_get_contents(const Arguments& args){
  2.  
  3. String::Utf8Value ag(args[0]);
  4. string file = string(*ag);
  5. string response="";
  6. ifstream f;
  7. f.open(file.c_str(), ios::in | ios::binary);
  8. if( f.fail() ){
  9. }
  10. else{
  11. while(!f.eof()){
  12. f >> response;
  13. }
  14.  
  15. }
  16. f.close();
  17. return String::New(response.c_str());
  18. }

file_put_contents

这里用简单的 c++语法实现写入档案

  1. Handle<Value> file_put_contents(const Arguments& args){
  2. if( args.Length()!=2 ){
  3. cerr << "Arguments : path , data";
  4. return Boolean::New(false);
  5. }
  6. String::Utf8Value ag(args[0]);
  7. String::Utf8Value d(args[1]);
  8. string path = string(*ag);
  9. string data = string(*d);
  10. ofstream f;
  11. f.open(path.c_str(), ios::out | ios::binary);
  12. if(f.is_open()){
  13. f << data ;
  14. f.close();
  15. }
  16. else{
  17. cerr << "Can not open file "<< path;
  18. return Boolean::New(false);
  19. }
  20. return Boolean::New(true);
  21. }
  22.  

create Template

将 file_get_contents 与 file_put_contents 绑进 ObjectTemplate

  1. Handle<ObjectTemplate> createBasicTemplate(){
  2. Local<ObjectTemplate> t = ObjectTemplate::New();
  3. t->Set("file_get_contents",FunctionTemplate::New(file_get_contents));
  4. t->Set("file_put_contents",FunctionTemplate::New(file_put_contents));
  5.  
  6. return t;
  7. }

file handle main test

  1. #include <v8.h>
  2. #include <string.h>
  3. #include <iostream>
  4. #include <fstream>
  5. using namespace std;
  6. using namespace v8
  7. v8::Handle<v8::String> ReadFile(const char* name);
  8. int main (){
  9. Handle<ObjectTemplate> global;
  10. HandleScope handle_scope;
  11. Handle<Context> context;
  12.  
  13. global = createBasicTemplate();
  14.  
  15. context= Context::New(NULL,global);
  16. Context::Scope context_scope(context);
  17. Handle<v8::String> source = ReadFile("file.js");
  18. Handle<Script> script = Script::Compile(source);
  19. Handle<Value> result = script->Run();
  20. // context.Dispose();
  21. String::Utf8Value str(result);
  22. script = Script::Compile(String::New("result"));
  23. result = script->Run();
  24. cout << *String::Utf8Value(result);
  25. return 0;
  26. }
  27.  

js 语法测试

  1. file_put_contents('t.txt',"测试写入档案");
  2. var result=file_get_contents('t.txt');
  3.  

回應 (Leave a comment)