ECMA script. Read .txt file content

Discussion forum for C++ and script developers who are using the QCAD development platform or who are looking to contribute to QCAD (translations, documentation, etc).

Moderator: andrew

Forum rules

Always indicate your operating system and QCAD version.

Attach drawing files, scripts and screenshots.

Post one question per topic.

Post Reply
sinase
Active Member
Posts: 47
Joined: Sat Jan 30, 2021 11:12 pm

ECMA script. Read .txt file content

Post by sinase » Thu Mar 04, 2021 8:12 am

Hello,

I have a new .dxf open and i like to export it a .dxf file by ECMA script, with the name of .txt file content. Is it possible do this by programming? For example, if i write on my .txt the word "helloworld", my .dxf exported will be helloworld.dxf.

//Begin
var action2 = RGuiAction.getByScriptFile("scripts/File/NewFile/NewFile.js");
if (!isNull(action2)) {
action2.slotTrigger();
}
var di = EAction.getDocumentInterface();
var document = di.getDocument();

/**
* I need to read .txt file content and save in "data" variable. This .txt would be in a local path of my computer.
*/

di.exportFile("/Users/jchueca/Desktop/" + data + ".dxf", "DXF 2000");
//End

Thank you very much.

User avatar
andrew
Site Admin
Posts: 9037
Joined: Fri Mar 30, 2007 6:07 am

Re: ECMA script. Read .txt file content

Post by andrew » Thu Mar 04, 2021 8:32 am

You can read the contents of a file into a string variable using this convenience function:

Code: Select all

include("scripts/library.js");

var str = readTextFile("/path/to/file.txt");
If the file cannot be found or cannot be read, undefined is returned.
Note that the file might contain line feed which will also be read and returned.

CVH
Premier Member
Posts: 3416
Joined: Wed Sep 27, 2017 4:17 pm

Re: ECMA script. Read .txt file content

Post by CVH » Thu Mar 04, 2021 8:55 am

Hi,
To read text I was thinking of a QTextStream ...

And that is exactly what readTextFile() from library.js does.
it reads a full text file: var contents = textStream.readAll();

If the file holds multiple entries you could also cycle trough it line by line.
var textLine = textStream.readLine();

Two simple examples:
..QCAD\scripts\Misc\Examples\IOExamples\ExRegisterFileImporter\ExRegisterFileImporter.js
..QCAD\scripts\Misc\MiscIO\ImportPoints\ImportPoints.js
Or you source them from Github.
Both under:
https://github.com/qcad/qcad/tree/master/scripts/Misc

Regards,
CVH

sinase
Active Member
Posts: 47
Joined: Sat Jan 30, 2021 11:12 pm

Re: ECMA script. Read .txt file content

Post by sinase » Thu Mar 04, 2021 9:17 am

Hello,

readTextFile() helped me.

Thanks!

Post Reply

Return to “QCAD Programming, Script Programming and Contributing”