在 Node.js 中复制到剪贴板?

发布于 2024-12-10 09:13:48 字数 84 浏览 0 评论 0原文

有没有办法可以在 Node.js 中复制到剪贴板?有什么模块或想法吗?我在桌面应用程序上使用 Node.js。希望这能澄清为什么我希望它能够实现这一目标。

Is there a way you can copy to clipboard in Node.js? Any modules or ideas what so ever? I'm using Node.js on a desktop application. Hopefully that clears up why I want it to be able to achieve this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

阳光下慵懒的猫 2024-12-17 09:13:48

对于 OS X:

function pbcopy(data) {
    var proc = require('child_process').spawn('pbcopy'); 
    proc.stdin.write(data); proc.stdin.end();
}

write() 可以采用缓冲区或字符串。字符串的默认编码为 utf-8。

For OS X:

function pbcopy(data) {
    var proc = require('child_process').spawn('pbcopy'); 
    proc.stdin.write(data); proc.stdin.end();
}

write() can take a buffer or a string. The default encoding for a string will be utf-8.

尤怨 2024-12-17 09:13:48

查看 clipboardy。它允许您跨平台复制/粘贴。它比另一个答案中提到的复制粘贴模块提到更加积极,它修复了许多问题该模块的问题。

import clipboardy from 'clipboardy';

// Copy
clipboardy.writeSync('

Check out clipboardy. It lets you copy/paste cross-platform. It is more actively maintained than the copy-paste module mentioned in another answer and it fixes many of that module's issues.

import clipboardy from 'clipboardy';

// Copy
clipboardy.writeSync('????');

// Paste
clipboardy.readSync();
//????
对岸观火 2024-12-17 09:13:48

Windows 中的最短路径:

const util = require('util');
require('child_process').spawn('clip').stdin.end(util.inspect('content_for_the_clipboard'));

Shortest way in Windows:

const util = require('util');
require('child_process').spawn('clip').stdin.end(util.inspect('content_for_the_clipboard'));
挽袖吟 2024-12-17 09:13:48

这是一个提供复制和粘贴功能的模块:https://github.com/xavi-/node-copy-paste

执行require("copy-paste").global()时,添加了两个全局函数:

> copy("hello") // Asynchronously adds "hello" to clipbroad
> Copy complete
> paste() // Synchronously returns clipboard contents
'hello'

像提到的许多其他答案一样,复制并粘贴到节点中需要调用外部程序。对于node-copy-paste,它会调用pbcopy/pbpaste(对于 OSX),xclip (对于Linux),以及 clip(适用于 Windows)。

当我在 REPL 中为一个业余项目做大量工作时,这个模块非常有帮助。不用说, copy-paste 只是一个命令行实用程序——它用于服务器工作。

Here's a module that provide copy and paste functions: https://github.com/xavi-/node-copy-paste

When require("copy-paste").global() is executed, two global functions are added:

> copy("hello") // Asynchronously adds "hello" to clipbroad
> Copy complete
> paste() // Synchronously returns clipboard contents
'hello'

Like many of the other answer mentioned, to copy and paste in node you need to call out to an external program. In the case of node-copy-paste, it calls out to pbcopy/pbpaste (for OSX), xclip (for linux), and clip (for windows).

This module was very helpful when I was doing a lot of work in the REPL for a side project. Needless to say, copy-paste is only a command line utility -- it is not meant for server work.

猫烠⑼条掵仅有一顆心 2024-12-17 09:13:48

剪贴板不是操作系统固有的。它是操作系统恰好运行的任何窗口系统的构造。因此,如果您希望它在 X 上工作,您将需要绑定到 Xlib 和/或 XCB。节点的 Xlib 绑定​​实际上存在:https://github.com/mixu/nwm。虽然我不确定它是否允许您访问 X 剪贴板,但您最终可能会编写自己的剪贴板。您将需要单独的窗口绑定。

编辑:如果你想做一些 hacky 的事情,你也可以使用 xclip:

var exec = require('child_process').exec;

var getClipboard = function(func) {
  exec('/usr/bin/xclip -o -selection clipboard', function(err, stdout, stderr) {
    if (err || stderr) return func(err || new Error(stderr));
    func(null, stdout);
  });
};

getClipboard(function(err, text) {
  if (err) throw err;
  console.log(text);
});

A clipboard is not inherent to an operating system. It's a construct of whatever window system the operating system happens to be running. So if you wanted this to work on X for example, you would need bindings to Xlib and/or XCB. Xlib bindings for node actually exist: https://github.com/mixu/nwm. Although I'm not sure whether it gives you access to the X clipboard, you might end up writing your own. You'll need separate bindings for windows.

edit: If you want to do something hacky, you could also use xclip:

var exec = require('child_process').exec;

var getClipboard = function(func) {
  exec('/usr/bin/xclip -o -selection clipboard', function(err, stdout, stderr) {
    if (err || stderr) return func(err || new Error(stderr));
    func(null, stdout);
  });
};

getClipboard(function(err, text) {
  if (err) throw err;
  console.log(text);
});
你如我软肋 2024-12-17 09:13:48

我设法通过创建一个不同的应用程序来处理这个问题来做到这一点。这当然不是最好的方法,但它确实有效。

我在 Windows 上创建了一个 VB.NET 应用程序:

Module Module1

    Sub Main()
        Dim text = My.Application.CommandLineArgs(0)
        My.Computer.Clipboard.SetText(text)
        Console.Write(text) ' will appear on stdout
    End Sub
End Module

然后在 Node.js 中,我使用 child_process.exec 运行 VB.NET 应用程序,并将要复制的数据作为命令行传递争论:

require('child_process').exec(
    "CopyToClipboard.exe \"test foo bar\"",

    function(err, stdout, stderr) {
        console.log(stdout); // to confirm the application has been run
    }
);

I managed to do so by creating a different application which handles this. It's certainly not the best way, but it works.

I'm on Windows and created a VB.NET application:

Module Module1

    Sub Main()
        Dim text = My.Application.CommandLineArgs(0)
        My.Computer.Clipboard.SetText(text)
        Console.Write(text) ' will appear on stdout
    End Sub
End Module

Then in Node.js, I used child_process.exec to run the VB.NET application, with the data to be copied passed as a command line argument:

require('child_process').exec(
    "CopyToClipboard.exe \"test foo bar\"",

    function(err, stdout, stderr) {
        console.log(stdout); // to confirm the application has been run
    }
);
捶死心动 2024-12-17 09:13:48

Mac 针对此用例有一个本机命令行 pbcopy

require('child_process').exec(
    'echo "test foo bar" | pbcopy',

    function(err, stdout, stderr) {
        console.log(stdout); // to confirm the application has been run
    }
);

Linux 的代码相同,但将 pbcopy 替换为 Xclipapt get install xclip

Mac has a native command line pbcopy for this usecase:

require('child_process').exec(
    'echo "test foo bar" | pbcopy',

    function(err, stdout, stderr) {
        console.log(stdout); // to confirm the application has been run
    }
);

Same code for Linux but replace pbcopy with Xclip (apt get install xclip)

邮友 2024-12-17 09:13:48

我发现这里或任何地方都没有适用于 Windows 的解决方案,因此重新发布 这个在 Google 搜索第 2 页的深处找到,该搜索使用 Windows 本机命令行 clip,并避免任何潜在的混乱使用命令行解决方法,例如 echo foo |像上面建议的那样进行剪辑。

  var cp = require("child_process");
  var child = cp.spawn('clip');
  child.stdin.write(result.join("\n"));
  child.stdin.end();

希望这对某人有帮助!

I saw there wasn't a solution here or anywhere obvious that worked for Windows, so reposting this one found in the depths of page 2 on Google search, which uses the Windows native command line clip, and avoids any potentially messy usage of command line workarounds such as echo foo | clip like suggested above.

  var cp = require("child_process");
  var child = cp.spawn('clip');
  child.stdin.write(result.join("\n"));
  child.stdin.end();

Hope this helps someone!

瞳孔里扚悲伤 2024-12-17 09:13:48

这就是您在 Windows 的 node-ffi 上执行此操作的方法,它直接与 Windows 的本机剪贴板 API。 (这意味着您还可以读取/写入不同的剪贴板格式)

var {
  winapi,
  user32,
  kernel32,
  constants
} = require('@kreijstal/winffiapi')
const GMEM_MOVEABLE=0x2;
var stringbuffer=Buffer.from("hello world"+'\0');//You need a null terminating string because C api.
var hmem=kernel32.GlobalAlloc(GMEM_MOVEABLE,stringbuffer.length);
var lptstr = kernel32.GlobalLock(hmem);
stringbuffer.copy(winapi.ref.reinterpret(lptstr, stringbuffer.length));
kernel32.GlobalUnlock(hmem);
if (!user32.OpenClipboard(0)){
    kernel32.GlobalLock(hmem);
    kernel32.GlobalFree(hmem);
    kernel32.GlobalUnlock(hmem);
    throw new Error("couldn't open clipboard");
}
user32.EmptyClipboard();
user32.SetClipboardData(constants.clipboardFormats.CF_TEXT, hmem);
user32.CloseClipboard();

This is how you would do this on node-ffi for windows, this interacts directly with the native clipboard API from windows. (Which means you can also read/write different clipboard formats)

var {
  winapi,
  user32,
  kernel32,
  constants
} = require('@kreijstal/winffiapi')
const GMEM_MOVEABLE=0x2;
var stringbuffer=Buffer.from("hello world"+'\0');//You need a null terminating string because C api.
var hmem=kernel32.GlobalAlloc(GMEM_MOVEABLE,stringbuffer.length);
var lptstr = kernel32.GlobalLock(hmem);
stringbuffer.copy(winapi.ref.reinterpret(lptstr, stringbuffer.length));
kernel32.GlobalUnlock(hmem);
if (!user32.OpenClipboard(0)){
    kernel32.GlobalLock(hmem);
    kernel32.GlobalFree(hmem);
    kernel32.GlobalUnlock(hmem);
    throw new Error("couldn't open clipboard");
}
user32.EmptyClipboard();
user32.SetClipboardData(constants.clipboardFormats.CF_TEXT, hmem);
user32.CloseClipboard();
π浅易 2024-12-17 09:13:48

如果您要将文件(而不是其内容)复制到剪贴板,请考虑以下事项:

对于 macOS:

let filePath; // absolute path of the file you'd like to copy

require('child_process').exec(  
  `osascript -e 'set the clipboard to POSIX file "${filePath}"'`,

  function (err, stdout, stderr) {
    console.log(stdout); // to confirm the application has been run
  }
);

对于 Windows:

const filePath; // absolute path of the file you'd like to copy

// Make a temporary folder
const tmpFolder = path.join(__dirname, `tmp-${Date.now()}`);
fs.mkdirSync(tmpFolder, { recursive: true });

// Copy the file into the temporary folder
const tmpFilePath = path.join(tmpFolder, path.basename(filePath));
fs.copyFileSync(filePath, tmpFilePath);

// To copy the contents of the folder in PowerShell,
// you need to add a wildcard to the end of the path
const powershellFolder = path.join(tmpFolder, '*');

require('child_process').exec(
  `Set-Clipboard -PATH "${powershellFolder}"`, { 'shell': 'powershell.exe' },

  function (err, stdout, stderr) {
    console.log(stdout); // to confirm the application has been run
  }
);

If you'd like to copy a file (not its contents) to the clipboard, consider the following:

For macOS:

let filePath; // absolute path of the file you'd like to copy

require('child_process').exec(  
  `osascript -e 'set the clipboard to POSIX file "${filePath}"'`,

  function (err, stdout, stderr) {
    console.log(stdout); // to confirm the application has been run
  }
);

For Windows:

const filePath; // absolute path of the file you'd like to copy

// Make a temporary folder
const tmpFolder = path.join(__dirname, `tmp-${Date.now()}`);
fs.mkdirSync(tmpFolder, { recursive: true });

// Copy the file into the temporary folder
const tmpFilePath = path.join(tmpFolder, path.basename(filePath));
fs.copyFileSync(filePath, tmpFilePath);

// To copy the contents of the folder in PowerShell,
// you need to add a wildcard to the end of the path
const powershellFolder = path.join(tmpFolder, '*');

require('child_process').exec(
  `Set-Clipboard -PATH "${powershellFolder}"`, { 'shell': 'powershell.exe' },

  function (err, stdout, stderr) {
    console.log(stdout); // to confirm the application has been run
  }
);
贱人配狗天长地久 2024-12-17 09:13:48

检查这个zeroclipboard

npm 安装零剪贴板

check this zeroclipboard

npm install zeroclipboard

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文