Count Files in File Upload Ftp Lua Script
- Introduction
- Using the content of a message to form the output file name
- Moving files around
- Sending files via FTP, FTPS (SSL/TLS)
- Recursive file search
- Where is the best place to phone call
net.xxx.init{}
Introduction
Using the APIs supplied by the Translator provides an incredibly powerful and convenient set of tools to handle custom requirements using file and FTP operations.
On the whole we recommend you consider using the Translator for well-nigh of your file handling needs considering it is so simple to use. Come across minimalism. You can even show the file settings through the Iguana dashboard using the APIs we supply.
Also run into the section on invoking external programs to see how you lot can find the current working directory and get the list of files in a directory.
Using the content of a message to class the output file name [top]
This example shows how easy information technology is to use the built Lua 'io' library to use the bulletin control ID to form the file name of the message. This is simply one example:
Because of the dynamic nature of the Translator surround it's easy to:
- Use data from any source to ascertain the file name
- Dynamically see the generated file proper noun
- Actually verify that the resulting file is generated as you would similar
It makes for a beautifully productive work flow and information technology's like shooting fish in a barrel to see the flow of data. Rather cool. Here'south the code in a format you can copy. Enjoy!
crave 'node' function master(Information) local Msg = hl7.parse{information=Data, vmd='example/demo.vmd'} local FileName = Msg.MSH[ten]..'.hl7' local F = io.open('D:temp'..FileName, "w") F:write(Data) F:shut() print('Wrote "'..FileName..'"') finish Tip: The file actions are active in the editor (test mode), which means you can create a large number of "test" files. One time your code is working correctly you may want to preclude this. Also you will need to disable this for a alive system, to preclude accidental updates.
The solution is simply to use iguana.isTest() to prevent the code from running.
Moving files around [acme]
Lua does not accept very many built-in file operations. Here are the few that it does have:
- os.remove(file) – Remove a file. Returns true if the file was removed. Returns nil, plus a string describing the mistake, if the file was not removed. Instance:
local Event, ErrorString = os.remove('foo.txt') if not Effect then print(ErrorString) end - os.rename(source, dest) – Renames and/or moves a file. Returns true if the rename/move was successful. Returns cipher, plus a string describing the mistake, if the rename/move failed. Example:
local Result, ErrorString = bone.rename('foo.txt', 'subdir/bar.txt') if not Issue so print(ErrorString) stop - io.open up(name, [mode]) – Opens a file, creating information technology if necessary, provided the 'mode' allows creation of the file. Returns a file handle object if the open was successful. Returns nix, plus a string describing the error, if the open was not successful. 'manner' is a string that is in the same format as the 'manner' statement to standard C role, fopen. The most mutual modes are:
- 'r' – read (the default mode). The file must exist.
- 'w' – write. This will create the file if necessary.
- 'a' – append. This will create the file if necessary.
- The file handle returned from io.open up has the post-obit operations:
- handle:close() – Closes the file. Information technology is always a adept thought to explicitly call this whenever you are done with the file.
- handle:flush() – Save any written data to the file.
- handle:lines() – Returns an iterator function which tin can exist used to iterate over each line in the file. Instance:
local File = io.open up('foo.txt') for Line in File:lines() practise impress(Line) finish - handle:read(…) – Read from the file. Past default, volition read one line from the file. To read all lines, pass specify '*a' equally the argument. For a complete list of valid arguments, meet the file:read entry in the lua reference manual.
- handle:write(…) – Writes all arguments to the file.
- Come across the lua reference manual for the less common operations, file:seek and file:setvbuf.
- os.execute(command) – Executes 'command', and returns a return code (zilch for success, non-zero if an error occurred). We volition run across in the section below how os.execute tin can be used for every other file performance.
Using os.execute() for Everything Else
os.execute can be used to practice pretty much anything you tin can imagine. But it does accept 1 limitation – y'all can't get the standard output of the command. Here is a basic wrapper of the office yous can use to become around this:
-- Execute a control. -- The start return value is the output from the command -- (or nil if there was no output). -- The 2nd is the returned status code from executing the control. -- function MyExecute(Command) -- We use os.tmpname(), a congenital-in Lua function, to give us a -- temporary file name. local TempFileName = os.tmpname() local Event = bone.execute(Command..' > '..TempFileName..' 2>&1') local TempFile = io.open(TempFileName) if TempFile then local CommandOutput = TempFile:read('*a') TempFile:close() os.remove(TempFileName) return CommandOutput, Result else return nil, Result finish end This writes the output of the command to a temporary file, then reads the file to become the output, and deletes the temporary file. Now the instance in Recursive file search tin can be simplified similar so:
-- Does a recursive search of the directory specified -- past Root, and returns the total path of the file with -- the name File, if it is found. Returns nil otherwise. -- function findFile(Root, File) render MyExecute('dir /S /B "'..Root..'" | find "'..File..'"') end So you tin can see, annihilation y'all can do from the command-line, you lot tin do with os.execute(). Other uses include, but are not express to:
- Copying files (using the MS 'copy' command, or the posix 'cp' command)
- Creating a directory (using the MS 'md' control, or the posix 'mkdir' command)
- Removing a directory (using the MS 'rd' command, or the posix 'rmdir' command)
Sending files via FTP, FTPS (SSL/TLS) [top]
Say you have the ways of getting the path to an image file in your file system. Here is a sample script for a "To Translator" component, showing how you tin use the net api to upload that file to a server via FTP/FTPS/SFTP:
-- The main function is the commencement function called from Iguana. -- The Data argument will incorporate the message to be processed. function main(FileId) local FileName = 'Images/'..FileId..'.tiff' local ImageFile = io.open up(FileName) if not ImageFile then -- TODO brand an email notification rule that sends emails -- whenever a log message starting with -- 'Epitome file does not exist' is found. impress('Image file does not exist: "'..FileName..'".') return else ImageFile:close() end -- set up up the connectedness and transport the file local Ftp = net.ftp.init{server='192.168.0.100',username='fred',password='hugger-mugger'} Ftp:put{local_path=FileName,remote_path='/ScanImages/'..FileId..'.tiff'} end In this example, I've just constructed the path from the ID that gets passed into the main function. This ID is produced from a "From Translator" component (see Polling a database, and generating CSV files). Note the "TODO" comment – you can ready an Iguana email notification dominion to send out an email when a specific problem is encountered.
For more information regarding "Details on Server SSL Certificates", please refer to: http://curl.haxx.se/docs/sslcerts.html
Recursive file search [top]
Because Lua has an extremely minimal interface, there is no built-in functions for many tasks. Withal, the bone.execute() function can be used to accomplish nearly anything. In this case, we volition use it to recursively search through a directory and its subdirectories to find the full path of a specified file, given its name. Here is my part:
-- Does a recursive search of the directory specified -- by Root, and returns the full path of the file with -- the proper noun File, if it is establish. Returns nil otherwise. -- function findFile(Root, File) local OutputFileName = File..'.fs' os.execute('dir /S /B "'..Root.. '" | find "'..File..'" > "'..OutputFileName..'"') local OutputFile = io.open(OutputFileName) local FullPath = OutputFile:read() OutputFile:close() os.remove(OutputFileName) return FullPath end This code is written for Windows. The /South flag makes the command search through subdirectories, and the /B flag makes only the plain file paths printed (and no other info on the file). For Posix, the following control will work:
os.execute('find "'..Root..'" | grep "'..File..'" > "'..OutputFileName..'"')
Where is the all-time identify to call net.xxx.init{} [summit]
We had this question come in our Forums: Is it better to call net.sftp.init{} at the beginning of the chief.lua file (so that information technology is only executed on channel first), or inside of main()?
The elementary answer is that it makes very little departure. The cyberspace.sftp.init{} phone call only caches the connection parameters, a separate connection is so opened and closed for each subsequent SFTP command.
In that location is a small-scale performance overhead depending on where the call is placed. When the call is outside main() it is but called once when the channel is started, if information technology is inside it is within master() then information technology is called for each bulletin, which is a marginally greater overhead.
Note: The same thing applies for net.ftp.init{} and cyberspace.ftps.init{}.
Please contact support at support@interfaceware.com if you lot need more help.
Source: https://help.interfaceware.com/v6/file-and-ftp-interfaces
0 Response to "Count Files in File Upload Ftp Lua Script"
Postar um comentário