Как заработать в сети internet
Вторник, 21-Май-2024, 10:10
Меню сайта

Форма входа

Категории раздела
Технические вопросы [12]
Спонсоры [2]
Общие [0]

Поиск

Друзья сайта
  • Úklid v Praze

  • Статистика



    Онлайн всего: 1
    Гостей: 1
    Пользователей: 0

    Главная » Статьи » Технические вопросы

    javascript. Запись и запуск файла из яваскрипта
    Рыба функции для записи в файл. Открывает (при отсутствии - создает) файл, записывает данные из переменной и закрывает. Проще потом преобразовать в класс.

    function fileWorks(fileName, filePath){
        //первичная инициализация
        this.fileName = fileName;
        this.filePath = filePath;
        this.file = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
        this.file.initWithPath(this.filePath);
        this.file.appendRelativePath(this.fileName);
        //проверка на существование true - есть, false - нет
        //TODO: проблема, что определяет каталоги как файлы...
        this.checkFile = function(){
        if(!this.file.exists())
            return false;
        return true;
        }
        //создание файла. возвращает false, если таковой уже есть
        this.createFile = function(){
            if(this.file.exists())
                return false;
            this.file.create(0x00, 0666);
            return true;
        }
        //удаление файла
        //TODO: разобраться с параметром
        this.deleteFile = function(){
            if(!this.file.exists())
                return false;
            this.file.remove(false);
            return true;
        }
        //запись в файл в конец
        this.writeToFile = function(text){
            this.stream = Components.classes['@mozilla.org/network/file-output-stream;1']
                    .createInstance(Components.interfaces.nsIFileOutputStream);
            this.stream.init(this.file, 0x02 | 0x10, 0664, 0);
            this.converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"]
                    .createInstance(Components.interfaces.nsIConverterOutputStream);
            this.converter.init(this.stream, "UTF-8", 0, 0);
            this.converter.writeString(text);
            this.converter.close();
            this.stream.close();
        }
        //запись в файл в конец с новой строки
        this.writeToFileLine = function(text){
            this.stream = Components.classes['@mozilla.org/network/file-output-stream;1'];
            this.stream = this.stream.createInstance(Components.interfaces.nsIFileOutputStream);
            this.stream.init(this.file, 0x02 | 0x10, 0664, 0);
            this.converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].
                createInstance(Components.interfaces.nsIConverterOutputStream);
            this.converter.init(this.stream, "UTF-8", 0, 0);
            this.converter.writeString("\u000D\u000A");
            this.converter.writeString(text);
            this.converter.close();
            this.stream.close();
        }
        //чтение файла полностью
        this.readFromFileAll = function(){
            this.stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                    .createInstance(Components.interfaces.nsIFileInputStream);
             this.stream.init(this.file,0x01, 00004, null);
            this.streamSize = Components.classes["@mozilla.org/scriptableinputstream;1"]
                    .createInstance(Components.interfaces.nsIScriptableInputStream);
             this.streamSize.init(this.stream);
             return this.streamSize.read( this.streamSize.available() );
        }
        //TODO: this.readFromFileLine = function(lineNumber){}
    }

    Создание объекта через writeFile = new fileWorks("имя файла", "путь к файлу");
    А запись через writeFile.writeToFile("текст");

    Рыба функции для запуска файла.


    function rnFile(){
        var fInit = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
        var pInit = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
        fInit.initWithPath("C:\\path\\run.exe");
        pInit.init(fInit);
        var args = ["arguments", ""];
        pInit.run(false, args, args.length);
    }

    Категория: Технические вопросы | Добавил: websponsory (06-Мар-2013)
    Просмотров: 518 | Комментарии: 1 | Рейтинг: 0.0/0 |
    Всего комментариев: 1
    1 websponsory  
    0
    Обновлено. Стараюсь сделать объект работы с файлами более универсальным.

    Добавлять комментарии могут только зарегистрированные пользователи.
    [ Регистрация | Вход ]
    Copyright MyCorp © 2024
    Бесплатный хостинг uCoz