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');