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)