node. js implements the function of copying text to clipboard

  • 2021-07-13 04:22:07
  • OfStack

Preface

Recently, I encountered a requirement in my work: I need to request back-end data, but I need to log in and get an token before requesting data. The login mode is to send post data to one json address. My previous practice is to use chrome plug-in postman to realize the login action. But then I accidentally discovered that postman memory occupation is extremely high! Even if I didn't use it. This makes me very unhappy.

Later, 1 thought, to achieve such a simple action, with such a heavy plug-in, is it too Low for me to be a front-end programmer who will nodejs? I'm embarrassed to tell people that I can nodejs!

So I spent some time writing a simple script. This article records the development process under 1.

Realization thought

The idea is to use the nodejs script to make the request and automatically copy the token in the returned result to the clipboard, so I just use it in debugging code, ctrl+v.

The idea is very simple, but there are many pits in realization.

nodejs is not copied directly to the clipboard's API!

Very simple function, but nodejs does not provide it. But don't despair, because nodejs can call system commands, and there are many commands in the system commands that can operate the clipboard.

After google, because the system is windows, we consider using clip in windows cmd command to realize the function of copying to clipboard.

nodejs Invoke System Command (cmd)

I.e. var exec = require(‘child_process').exec Then you can call it like a normal function 1, such as: exec(‘echo 111');

Pit of clip Command

In cmd, the simplest command to copy text to the clipboard is: echo 123456 | clip . Originally, spell out such a sentence in nodejs and give it to child_process.exec Just execute it. But as a result of this command, there is an bug that I can't stand: the copied text, and finally there is a newline character (caused by echo)! It is impossible for me to press the delete key several times after ctrl+v to ctrl+s!

At that time, it made me very entangled. I was surprised that Microsoft didn't even make such a simple command. But helpless things still have to be done, only to continue to find solutions. So there is the following way without echo:


<nul (set/p z=123456) | clip

This method is 10 points awkward, pay attention to the first one < It's not that I typed the wrong word! The general idea is to set a variable named p (this name can be changed at will) with a value of 12346 through set command, and immediately call clip to copy the value of this variable. However, the value copied by this method still has bug: 1 more space at the end! Although there are no spaces in your code, there are copied spaces! Can't go away! At that time, I was going to scold my mother! If there is no line break, there will be spaces. Can you rely on some spectrum?

Trouble and safe final realization

Finally, I tried a way of thinking: after getting the text to be copied, generate a temporary file and put the text in; Generate a batch file, call clip command in the batch file, and copy the contents of that text file; Finally, delete the temporary text file and batch file.

What I thought at that time was, if this method is not perfect, I will abandon nodejs and vote for python!

Fortunately, the copied text is finally normal, with no newline characters and no spaces.

The code is as follows, and the request package is used to facilitate the request:


'use strict';

var request = require('request');
var fs = require('fs');

var exec = require('child_process').exec;
var execFile = require('child_process').execFile;
request({
 method: 'POST',
 uri:'http://web.test1.com/mgw/login.json',
 headers: {
  'Content-Type':'application/json'
 },
 body: JSON.stringify({
  "loginname":"lixing1@0101005",
  "pw":"aebc3ebee2f0c8b08b43d26c2b0055b19caeaf4a",
  "res":"web"
 })
 }, function (err, result, body) {
 console.log(body);
 body = JSON.parse(body);
 copyToClipboard(body.token, function (text, stdout) {
  console.log('token copy successed!', text, stdout);
 })
});


//  Simply copy text to the clipboard function, the arguments are text in turn, and the successful callback 
var copyToClipboard = function(text, func) {
 //  This copy has a newline character at the end, which is not required 
 'echo ' + text + ' | clip';
 //  This copy has a space at the end, and it will make do with it 
 '<nul (set/p z=' + text + ') | clip';

 //  This way is the most perfect, but the most troublesome 
 //  Will generate 1 Batch files, 1 Text files, copy the contents of a file as a batch file, and then delete two files. 
 var temp = 'txt_' + Date.now() + '.txt';

 var str = `@echo off
<nul (set/p z=${text}) > ${temp} 
clip < ${temp} 
del ${temp}
`;
//  If this sentence is added to batch processing, it will cause an error, although it can be executed ( Duplicate ) Success. The reason should be, del When the batch file itself is processed, nodejs Still using him 
// 'del "%~f0"';
 var cmdFile = 'ttzkxlcjv.cmd';
 fs.writeFile(cmdFile, str);
 exec(cmdFile, function(err, stdout, stderr) {
 if (err || stderr) return console.log(err, stdout, stderr);
 //  Use nodejs Delete a file 
 fs.unlink(cmdFile);
 func(text, stdout);
 });
};

This involves another usage of cmd clip, namely clip < a_text.txt This will copy the contents of the following file. There is also a small pit in it. That is, in the batch file, add del "%~f0" Delete itself, originally can be used, but in nodejs, it will report an error. Later, I guess it should be because the batch file is still referenced by nodejs when it executes the command to delete itself, and the result is reported to be an error. Later, only the that calls nodejs fs.unlink Command, delete the batch file.

Summarize

By implementing this function, I learned how to use Request packages, invoke system commands, and use clip. Indeed, real demand is the strongest productivity.

It is much simpler to implement this function in linux or mac system.

clip command can not only copy text, you can explore under.

Preparation: Recently, it is too much trouble to ask for my own ctrl + v every time, so I use fs. readFile and fs. writeFile to write the requested token directly to my configuration file. The above clipboard function is useless, but I think it is very suitable to record this experience.

Well, the above is the whole content of this article. I hope the content of this article can bring 1 certain help to your study or work. If you have any questions, you can leave a message for communication.


Related articles: