Randolf's blog

代码片段

2025-06-29
javascriptshell
2分钟
205字

将 ASCII 码转换为字符

1
const numbersToText = (numbers) => {
2
let text = "";
3
for (let i = 0; i < numbers.length; i++) {
4
text += String.fromCharCode(numbers[i]); // 将 ASCII 码转换为字符
5
}
6
return text;
7
};
8
9
console.log(numbersToText("104,101,108,108,111,32,119,111,114,108,100".split(",")));
10
// "hello world"

将字符转换为 ASCII 码

1
const textToNumbers = (text) => {
2
const numbers = [];
3
for (let i = 0; i < text.length; i++) {
4
numbers.push(text.charCodeAt(i)); // 将字符转换为 ASCII 码
5
}
6
return numbers;
7
};
8
9
console.log(textToNumbers("hello world").join(","));
10
// "104,101,108,108,111,32,119,111,114,108,100"

MacOS 关闭自动睡眠

Terminal window
1
sudo pmset -a disablesleep 1

获取目录下文件

1
const fs = require("fs");
2
const path = require("path");
3
4
function getAllFiles(dirPath, arrayOfFiles) {
5
const files = fs.readdirSync(dirPath);
6
7
arrayOfFiles = arrayOfFiles || [];
8
9
files.forEach(function (file) {
10
if (fs.statSync(path.join(dirPath, file)).isDirectory()) {
11
arrayOfFiles = getAllFiles(path.join(dirPath, file), arrayOfFiles);
12
} else {
13
arrayOfFiles.push(path.join(dirPath, file));
14
}
15
});
16 collapsed lines
16
17
return arrayOfFiles;
18
}
19
20
const directoryPath = "~/Desktop"; // 换为你的目录路径
21
const allFiles = getAllFiles(directoryPath);
22
23
console.log(allFiles);
24
/**
25
[
26
"/Users/username/Desktop/file1.txt",
27
"/Users/username/Desktop/folder1/file2.txt",
28
"/Users/username/Desktop/folder1/subfolder/file3.txt",
29
"/Users/username/Desktop/folder2/file4.txt"
30
]
31
*/

Fetch IP

1
fetch('https://api.ipify.org?format=json')
2
.then((response) => response.json())
3
.then((data) => console.log('Your IP address is: ', data.ip))
4
.catch((error) => console.error('Error fetching IP address: ', error));
5
// "Your IP address is: 1.1.1.1"
本文标题:代码片段
文章作者:Randolf Zhang
发布时间:2025-06-29
Copyright 2025
站点地图