Haven't written a blog for a long time, because recently in using react+express to make a own tool-type website (in fact, to seize the Treasure Island snap device)
And then because you often have to change, but also put on the server for testing. Always want to Webpack, and then manually upload the file, patience, simply search the next, directly write a file can detect changes and automatically upload the script is good.
First of all, we use NPM to install two modules that others have packaged.
NPM Install ssh2-sftp-clientnpm Install gaze
The function of the first module is the SFTP upload file,
The role of the second module is to listen for file changes. Of course, you can also use node's own FS module.
The usage of these two modules is here: ssh2-sftp-client Gaze
After installation, the first step is to listen to the changes in the file, because my files have been built using Webpack, so the only file changes, there will be no file increase, so here only need to use changed, other usage please refer to the above link, are similar
Gaze ([' Your file path/*.* ', ' You can also use an array to listen to multiple folders/app.js '],function(err, watcher) { Letwatched = This. watched (); //changes to the listening file This. On (' changed ',(filepath) = {//Romotepath is the remote location of my files LetRomotepath = '/root ' + filepath.substr (15); //put is the function to upload the file, the following will sayput (Filepath,romotepath); Console.log (filepath+ ' was changed '); });});
And then we start writing the function of our upload file.
function put (Localpath,romotepath) {Let SFTP = new Client (); Sftp.connect ({host: ' Your server address ' ' ports, the word" username: ' connected user name ' ' password '
Well, don't forget to introduce modules where our files begin.
Let Client = require (' ssh2-sftp-client '= require (' gaze ');
Next, let's experiment. Come to our folder Webpack a bit
Sure enough you can see that the changes have been made and the upload is complete. Upload takes time, please wait patiently.
Come to our server, sure enough the latest modification time has become now.
Since then I do not have to upload a. Each time you want to modify the direct. Open a window to start the script, you can happily encoded.
Monitor file changes with Nodejs and upload to server using SFTP