Is it possible to watch for ONLY new file creation events using nodemon js or npm or any other packages? For example: in a project every time a new file is created certain other script has to be run to perform additional tasks just for one time setup.
Currently, the way it is set using nodemon runs the script every time a file changes, but this wasteful of resources (CPU/Memory) because the setup is one time thing and only needed when a new file is created.
Hope that makes sense if not here is a simple example.
Say, for example every time a new file is created we want to run a script which automatically creates some record or link to this file -- which only needs to be done once.
Alternative: If not possible in nodemon or with npm packages, are there alternatives such as directly using shell scripting (windows + linux) or python?
Python is an easy way!
Use watchdog
install by pip install watchdog
Try this script and modify the "on_created" function to do the things you want. You can use os.system("some script") to call another script, or subprocess.call(["node", "test.js"]).
import subprocess
import os
import sys
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class CustomHandler(FileSystemEventHandler):
"""Logs all the events captured."""
def on_moved(self, event):
super(CustomHandler, self).on_moved(event)
what = 'directory' if event.is_directory else 'file'
print("Moved {}: from {} to {}".format(what, event.src_path,
event.dest_path))
def on_created(self, event):
super(CustomHandler, self).on_created(event)
what = 'directory' if event.is_directory else 'file'
print("Created {}: {}".format(what, event.src_path))
def on_deleted(self, event):
super(CustomHandler, self).on_deleted(event)
what = 'directory' if event.is_directory else 'file'
print("Deleted {}: {}".format(what, event.src_path))
def on_modified(self, event):
super(CustomHandler, self).on_modified(event)
what = 'directory' if event.is_directory else 'file'
print("Modified {}: {}".format(what, event.src_path))
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = CustomHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=False)
observer.start()
print("Watchdog started...")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Hope this helps :)