如何在 HTML canvas 中加載圖像

我正在使用 canvas npm 套件以 Canvas API 的方式在伺服器端繪製圖像。 注意:這是 Node.js 中在 canvas 中處理圖像的方式,不同於網頁瀏覽器中的處理方式。 載入 loadImage() 函式: const { createCanvas, loadImage } = require('canvas') 建立 canvas: const width = 1200 const height = 630 const canvas = createCanvas(width, height) const context = canvas.getContext('2d') 接下來呼叫 loadImage(),當圖像載入完成時它將返回一個 Promise: loadImage('./logo.png').then(image => { }) 也可以在 async 函式中使用: const image = await loadImage('./logo.png') 獲得圖像後,使用 drawImage 函式,並傳遞 x、y、width 和 height 參數: context.drawImage(image, 340, 515, 70, 70)

如何在 macOS 上解決安裝 Node `canvas` 的問題

我想使用Node.js的canvas NPM包,但是執行npm install canvas會出現以下錯誤訊息: npm ERR! code 1 npm ERR! path /Users/flaviocopes/dev/old/generate-images-posts/node\_modules/canvas npm ERR! command failed npm ERR! command sh -c node-pre-gyp install --fallback-to-build npm ERR! Failed to execute '/opt/homebrew/Cellar/[[email protected]](/cdn-cgi/l/email-protection)/16.14.2/bin/node /opt/homebrew/Cellar/[[email protected]](/cdn-cgi/l/email-protection)/16.14.2/lib/node\_modules/npm/node\_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/Users/flaviocopes/dev/old/generate-images-posts/node\_modules/canvas/build/Release/canvas.node --module\_name=canvas --module\_path=/Users/flaviocopes/dev/old/generate-images-posts/node\_modules/canvas/build/Release --napi\_version=8 --node\_abi\_napi=napi --napi\_build\_version=0 --node\_napi\_label=node-v93' (1) npm ERR! node-pre-gyp info it worked if it ends with ok npm ERR! node-pre-gyp info using [[email protected]](/cdn-cgi/l/email-protection) npm ERR! node-pre-gyp info using [[email protected]](/cdn-cgi/l/email-protection) | darwin | arm64 npm ERR!...

如何在 Node.js 中使用 import 語法引入 .env 檔案

假設您已經設定了一個使用 ES 模塊的 Node.js 項目,並且想要使用 .env 檔案來存儲一個密碼,格式如下: PASSWORD=secret 您希望在 Node.js 腳本中能夠訪問這個密碼。 以下是如何實現的方法。 首先,安裝 dotenv 包: npm i dotenv 然後在代碼中使用以下內容: import * as dotenv from 'dotenv' dotenv.config() console.log(process.env.PASSWORD) 這需要假設您使用 ES 模塊(如果不是,只需在 package.json 文件中添加 "type": "module", 即可)。

如何在 Node.js 中創建空文件

發現如何在 Node.js 的文件系統文件夾中創建一個空文件 fs 內置模塊提供的 fs.openSync() 方法是最佳選擇。 它返回一個文件描述符: const fs = require('fs') const filePath = './.data/initialized' const fd = fs.openSync(filePath, 'w') w 標誌確保在文件不存在時創建文件,如果文件存在,則用新文件覆蓋它,覆蓋其內容。 使用 a 標誌可以避免覆蓋。如果文件不存在,仍然創建該文件。 如果不需要文件描述符,可以在 fs.closeSync() 調用中包裝該調用以關閉文件: const fs = require('fs') const filePath = './.data/initialized' fs.closeSync(fs.openSync(filePath, 'w'))

如何在 Node.js 中執行 Shell 命令

以下介紹如何在 Node.js 腳本中執行 Shell 命令。 首先,從 child_process 中導入 child 模組: import * as child from 'node:child_process'; // 或者 const child = require('node:child_process'); 然後,你可以像這樣調用 child.exec(): child.exec(`mkdir test`);

如何在 Node.js 中清空文件夾

如何在 Node.js 腳本中刪除文件夾中的所有文件 我需要在 Node.js 腳本中刪除文件夾中的所有文件。 我尋找了最佳解決方案,結果發現可以使用 fs-extra 库。 先安裝它: npm install fs-extra 然后導入該庫: import fsExtra from 'fs-extra' 最後使用 emptyDirSync() 方法,如下所示: const folder = './public/images' fsExtra.emptyDirSync(folder)

如何在 Node.js 中生成子進程

了解如何在 Node.js 中生成子進程 Node.js 提供了child_process模組,它提供了生成子進程的功能。 引入該模組,並從中獲取spawn函數: const { spawn } = require('child\_process') 然後你可以調用spawn()函數,並傳遞2個參數。 第一個參數是要運行的命令。 第二個參數是一個包含選項列表的數組。 這是一個例子: spawn('ls', ['-lh', 'test']) 在這個例子中,你運行ls命令,並指定了2個選項:-lh和test。這將生成命令ls -lh test,結果會顯示有關該文件的詳細信息: -rw-r--r-- 1 flaviocopes staff 6B Sep 25 09:57 test spawn()函數的返回值是ChildProcess類的實例,用於識別生成的子進程。 這是一個稍微複雜一些的例子,完全可運行。我們在test文件上設置監聽,每當它發生變化時,就在它上運行ls -lh命令: 'use strict' const fs = require('fs') const { spawn } = require('child\_process') const filename = 'test' fs.watch(filename, () => { const ls = spawn('ls', ['-lh', filename]) }) 還有一個缺少的步驟。我們必須將子進程的輸出 pipe 到主進程,否則我們將無法看到它的任何輸出。 我們可以通過在子進程的stdout屬性上調用pipe()方法來實現: 'use strict' const fs = require('fs') const { spawn } = require('child\_process') const filename = 'test' fs....

如何在 Node.js 中處理檔案上傳

本文將教你如何使用 Node.js,特別是 Express,來處理檔案上傳。 首先,安裝 express-fileupload npm 模組: npm install express-fileupload 然後將它加入至中介軟體: import fileupload from 'express-fileupload' // 或者 const fileupload = require('express-fileupload') 在你建立了 Express 應用程式之後,加入以下程式碼: app.use( fileupload(), //... 這是必要的,否則伺服器將無法解析檔案上傳。 現在上傳的檔案將會在 req.files 中提供。如果你忘記加入這個中介軟體,req.files 會是 undefined。 以下是處理檔案的最小程式碼範例: app.post('/saveImage', (req, res) => { const image = req.files.myFile const path = __dirname + '/images/' + image.name image.mv(path, (error) => { if (error) { console.error(error) res.writeHead(500, { 'Content-Type': 'application/json' }) res.end(JSON.stringify({ status: 'error', message: error })) return } res....

如何在 Node.js 的回調函數中使用 promises 和 await

大部分的 Node.js API 在還沒有 promises 的時候就已經建立了,在這些 API 中,使用了回調函數的解決方案。 一般的 Node.js API 使用方式如下: doSomething(param, (err, result) => { }) 這個也同樣適用於一些庫,例如 node-redis。當我在一個項目中使用它時,到了某個時候我真的需要把所有的回調函數都移除掉,因為我有太多層次的嵌套回調函數,這種情況下就會陷入所謂的 “回調地獄”。 另外,有時候必須避免使用回調函數,因為你需要從函數中返回函數調用的結果。如果這個結果是通過回調函數返回的,那麼想要獲取結果的唯一方法就是將它作為另一個函數的參數返回,進而持續進行回調函數的操作。 const myFunction = () => { doSomething(param, (err, result) => { return result //無法從 `myFunction` 中返回這個結果 }) } const myFunction = callback => { doSomething(param, (err, result) => { callback(result) //不行 }) } myFunction(result => { console.log(result) }) 但是,有一個簡單的解決方案,這也是由 Node.js 自身提供的。我們可以通過使用內置的 util 模塊中的 promisify 方法 “promisify” 一個不支援 promises 的函數(以及相應的 async/await 語法)。...

如何在Node.js中使用import

如果您正在使用Node.js,並希望停止使用require(),改用ES模塊的import語法,則需要進行以下操作。 在package.json文件中添加"type": "module",如下所示: { "name": "projectname", "version": "1.0.0", ...剩餘的文件內容 } 改為: { "name": "projectname", "type": "module", "version": "1.0.0", ...剩餘的文件內容 } 就這樣! 現在您可以使用import來引入模塊,例如: import fs from 'fs'