### Install rustup Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Download and install rustup, the Rust toolchain installer. ```bash $ curl https://sh.rustup.rs -sSf | sh ``` -------------------------------- ### Rustup Installation Options Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md After installing rustup, you will be prompted with options to proceed with the installation, customize it, or cancel. ```bash 1) Proceed with installation (default) 2) Customize installation 3) Cancel installation ``` -------------------------------- ### Install nvm Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Download and install the Node Version Manager (nvm). Close and reopen your terminal after installation. ```bash $ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash ``` -------------------------------- ### Running Node.js Project with npm start Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Demonstrates how to execute a Node.js project using the 'npm start' command. ```bash $ npm start > hello-world@0.1.0 start /Users/pipo/workspace/rust-for-node-developers/package-manager/meta-data/node > node src Hello world! ``` -------------------------------- ### Comprehensive File Reading with Detailed Error Handling Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md This is a more verbose example demonstrating detailed error handling for file operations, including opening, getting metadata, reading, and converting to a string, using `match` statements for each step. ```rust use std::error::Error; use std::fs::File; use std::io::Read; use std::str::from_utf8; fn read_file(path: &str) -> String { let mut file = match File::open(path) { Err(err) => panic!("Couldn't open: {}", err.description()), Ok(value) => value, }; let stat = match file.metadata() { Err(err) => panic!("Couldn't get stat: {}", err.description()), Ok(value) => value, }; let mut buffer = vec![0; stat.len() as usize]; match file.read(&mut buffer) { Err(err) => panic!("Couldn't read: {}", err.description()), Ok(_) => (), }; match from_utf8(&buffer) { Err(err) => panic!("Couldn't convert buffer to string: {}", err.description()), Ok(value) => value.to_string(), } } fn main() { let hello = read_file("hello.txt"); let world = read_file("world.txt"); println!("Content is: {} and {}", hello, world); } ``` -------------------------------- ### Example package-lock.json Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md A minimal example of a package-lock.json file generated for a Node.js project. ```json { "name": "hello-world", "version": "0.1.0", "lockfileVersion": 1 } ``` -------------------------------- ### Rust Main Function Setup Source: https://github.com/unite-network/rust-for-node-developers/blob/master/http-requests/README.md Basic setup for making asynchronous HTTP requests in Rust using hyper. It initializes the runtime and defines a placeholder for the request function. ```rust use hyper::rt::{run, Future, Stream}; use hyper::{Client, Request}; use hyper_tls::HttpsConnector; use std::str::from_utf8; fn main() { run(get()); } fn get() -> impl Future { // more code here } ``` -------------------------------- ### Verify rustup Installation Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Check if rustup was installed correctly and display its version. ```bash $ rustup --version rustup 1.16.0 (beab5ac2b 2018-12-06) ``` -------------------------------- ### Install Node.js Project Dependency Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Installs the 'rfnd-hello-world' package as a runtime dependency for a Node.js project using npm. ```bash $ npm install --save rfnd-hello-world ``` -------------------------------- ### Install Specific Rust Version Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Install a specific version of Rust using rustup. This process downloads and installs the necessary components. ```bash $ rustup install 1.29.0 info: syncing channel updates for '1.29.0-x86_64-apple-darwin' info: latest update on 2018-09-13, rust version 1.29.0 (aa3ca1994 2018-09-11) info: downloading component 'rustc' 57.7 MiB / 57.7 MiB (100 %) 2.1 MiB/s ETA: 0 s info: downloading component 'rust-std' 45.8 MiB / 45.8 MiB (100 %) 2.4 MiB/s ETA: 0 s info: downloading component 'cargo' 3.3 MiB / 3.3 MiB (100 %) 2.3 MiB/s ETA: 0 s info: downloading component 'rust-docs' 8.2 MiB / 8.2 MiB (100 %) 3.6 MiB/s ETA: 0 s info: installing component 'rustc' info: installing component 'rust-std' info: installing component 'cargo' info: installing component 'rust-docs' 1.29.0-x86_64-apple-darwin installed - rustc 1.29.0 (aa3ca1994 2018-09-11) ``` -------------------------------- ### Verify nvm Installation Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Check if nvm was installed successfully by displaying its version. ```bash $ nvm --version 0.33.11 ``` -------------------------------- ### Check npm Version Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Use this command to check your installed npm version. It's useful for verifying setup or troubleshooting. ```bash $ npm --version 6.4.1 ``` -------------------------------- ### Install Specific Node.js Version Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Install a specific version of Node.js using nvm. This command also switches to the installed version. ```bash $ nvm install v10.14.2 ``` -------------------------------- ### Verify Node.js Installation Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Check the installed Node.js version in your terminal. ```bash $ node --version v10.14.2 ``` -------------------------------- ### Switch Node.js Version Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Manually switch to a different installed Node.js version. ```bash $ nvm use v4.4.5 Now using node v4.4.5 (npm v2.15.5) ``` -------------------------------- ### package.json Configuration for Node.js Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Defines the main entry file and start script for a Node.js package. Used when running '$ npm start'. ```json { // ...your previous code "main": "src/index.js", "scripts": { "start": "node src/index.js" } } ``` -------------------------------- ### Rust Installation Confirmation Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Confirmation message after Rust is installed, indicating the installed version and instructions for updating the PATH. ```bash stable installed - rustc 1.31.0 (abe02cefd 2018-12-04) Rust is installed now. Great! To get started you need Cargo's bin directory ($HOME/.cargo/bin) in your PATH environment variable. Next time you log in this will be done automatically. To configure your current shell run source $HOME/.cargo/env ``` -------------------------------- ### Running Node.js Project Silently with npm -s start Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Shows how to run a Node.js project with reduced npm output using the '-s' flag. ```bash $ npm -s start Hello world! ``` -------------------------------- ### Run Node.js Script Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Execute the Node.js script using npm start. This command runs the script defined in the package.json's start script. ```bash $ npm -s start ``` -------------------------------- ### Node.js package.json Scripts Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Defines 'start' and 'build' scripts in a Node.js package.json file. ```json { "scripts": { "start": "npm run build && node dist", "build": "tsc --build src" } } ``` -------------------------------- ### Example Cargo.lock Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md A minimal example of a Cargo.lock file generated for a Rust project. ```toml [[package]] name = "hello-world" version = "0.1.0" ``` -------------------------------- ### Rust Debug Logging Example Source: https://github.com/unite-network/rust-for-node-developers/blob/master/parse-json/README.md This example shows how to use the `{:?}` and `{:#?}` format specifiers with the `println!` macro to log custom structs that implement the `Debug` trait. `{:#?}` provides pretty-printed output. ```bash $ cargo -q run Result is: Result is: [ Repository { name: "afpre", description: Some( " CLI for the AWS Federation Proxy" ), fork: true }, Repository { name: "ajv", description: Some( "The fastest JSON schema Validator. Supports v5 proposals" ), fork: true }, ... ] ``` -------------------------------- ### Install TypeScript as a Dev Dependency Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Install TypeScript using npm. This is a development dependency, not required at runtime. ```bash $ npm install --save-dev typescript ``` -------------------------------- ### Rust HttpsConnector and Client Setup Source: https://github.com/unite-network/rust-for-node-developers/blob/master/http-requests/README.md Configures an HttpsConnector for HTTPS requests and builds a hyper Client. Note the use of unwrap() as '?' is not directly supported in Futures. ```rust fn get() -> impl Future { // 4 is number of blocking DNS threads let https = HttpsConnector::new(4).unwrap(); let client = Client::builder().build(https); let req = Request::get("https://api.github.com/users/donaldpipowitch") .header("User-Agent", "Mercateo/rust-for-node-developers") .body(hyper::Body::empty()) .unwrap(); // more coded here } ``` -------------------------------- ### Node.js package.json Manifest Example Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md A typical package.json file for a Node.js project without dependencies. It includes metadata like name, version, author, and license. ```json { "name": "hello-world", "version": "0.1.0", "author": "John Doe (https://github.com/john.doe)", "contributors": [ "Jane Doe (https://github.com/jane.doe)" ], "private": true, "description": "This is just a demo.", "license": "MIT OR Apache-2.0", "keywords": ["demo", "test"], "homepage": "https://github.com/john.doe/hello-world", "repository": { "type": "git", "url": "https://github.com/john.doe/hello-world" }, "bugs": "https://github.com/john.doe/hello-world/issues" } ``` -------------------------------- ### Install Node.js Type Declarations Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Install type declarations for Node.js built-in modules using npm. This is necessary for TypeScript to recognize modules like 'fs'. ```bash $ npm install --save-dev @types/node ``` -------------------------------- ### Using expect() with Custom Error Messages Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md This example shows how to use `expect()` which functions similarly to `unwrap()` but allows for custom error messages when an error occurs. ```rust fn read_file(path: &str) -> String { read_to_string(path).expect("Couldn't read.") } ``` -------------------------------- ### Rust Cargo.toml Manifest Example Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md A Cargo.toml file for a Rust project, mirroring the structure of package.json. It includes essential metadata like package name, version, and authors. ```toml [package] name = "hello-world" version = "0.1.0" authors = ["John Doe ", "Jane Doe "] publish = false description = "This is just a demo." license = "MIT OR Apache-2.0" keywords = ["demo", "test"] homepage = "https://github.com/john.doe/hello-world" repository = "https://github.com/john.doe/hello-world" documentation = "https://github.com/john.doe/hello-world" ``` -------------------------------- ### Add Serde Dependencies to Cargo.toml Source: https://github.com/unite-network/rust-for-node-developers/blob/master/parse-json/README.md Add the serde and serde_json crates to your Cargo.toml file to enable JSON parsing and derive macros. This example shows how to include specific features for serde. ```diff [package] -name = "http-requests" +name = "parse-json" version = "1.0.0" publish = false [dependencies] hyper = "0.12.21" hyper-tls = "0.3.1" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" ``` -------------------------------- ### Rust Attributes Example Source: https://github.com/unite-network/rust-for-node-developers/blob/master/parse-json/README.md Demonstrates the usage of Rust attributes, including how they are applied to items like structs and functions. Attributes can modify the behavior or meaning of the code they are attached to. ```rust #[hello] struct SomeStruct; fn some_function() { #![world] } ``` -------------------------------- ### Check Cargo Version Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md This command displays the installed Cargo version. It typically matches the Rust compiler version. ```bash $ cargo --version cargo 1.31.0 (339d9f9c8 2018-11-16) ``` -------------------------------- ### Set Default Node.js Version Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Set a default Node.js version that will be used every time a new terminal session starts. ```bash $ nvm alias default v4.4.5 default -> v4.4.5 ``` -------------------------------- ### Parse JSON Response into a Vector of Repositories Source: https://github.com/unite-network/rust-for-node-developers/blob/master/parse-json/README.md Integrates JSON parsing into an HTTP request example. This snippet shows how to deserialize a JSON string, expected to be a list of repositories, into a `Vec` using `serde_json::from_str`. ```diff use hyper::rt::{run, Future, Stream}; use hyper::{Client, Request}; use hyper_tls::HttpsConnector; +use serde::Deserialize; use std::str::from_utf8; +#[derive(Deserialize, Debug)] +struct Repository { + name: String, + description: Option, + fork: bool, +} fn main() { run(get()); } fn get() -> impl Future { // 4 is number of blocking DNS threads let https = HttpsConnector::new(4).unwrap(); let client = Client::builder().build(https); - let req = Request::get("https://api.github.com/users/donaldpipowitch") + let req = Request::get("https://api.github.com/users/donaldpipowitch/repos") .header("User-Agent", "Mercateo/rust-for-node-developers") .body(hyper::Body::empty()) .unwrap(); client .request(req) .and_then(|res| { let status = res.status(); - let buf = res.into_body().concat2().wait().unwrap(); - println!("Response: {}", from_utf8(&buf).unwrap()); if status.is_client_error() { panic!("Got client error: {}", status.as_u16()); } if status.is_server_error() { panic!("Got server error: {}", status.as_u16()); } + let buf = res.into_body().concat2().wait().unwrap(); + let json = from_utf8(&buf).unwrap(); + let repositories: Vec = serde_json::from_str(&json).unwrap(); + println!("Result is:\n{{:#?}}", repositories); Ok(()) }) .map_err(|_err| panic!("Couldn't send request.")) } ``` -------------------------------- ### Basic GET Request with Node.js HTTPS Module Source: https://github.com/unite-network/rust-for-node-developers/blob/master/http-requests/README.md This snippet shows a basic GET request to the GitHub API using Node.js's built-in 'https' module. It handles response data and errors. ```typescript import { get } from 'https'; const host = 'api.github.com'; const path = '/users/donaldpipowitch'; get({ host, path }, (res) => { let buf = ''; res.on('data', (chunk) => (buf = buf + chunk)); res.on('end', () => console.log(`Response: ${buf}`)); }).on('error', (err) => { throw `Couldn't send request.`; }); ``` -------------------------------- ### Getting File Metadata in Rust Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Retrieves the metadata (like size) of the opened file. Errors during metadata retrieval are handled with `panic!`. ```rust let stat = match file.metadata() { Err(err) => panic!("Couldn't get stat: {}", err.description()), Ok(value) => value, }; ``` -------------------------------- ### JavaScript Prototype Manipulation Example Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Illustrates how JavaScript's prototype manipulation can be conceptually similar to Rust traits for adding methods, though it's generally discouraged in JS. ```javascript import './get-second-item'; const two = [1, 2, 3].getSecondItem(); console.log(two); // logs `2` ``` ```javascript Array.prototype.getSecondItem = function getSecondItem() { return this[1]; }; ``` -------------------------------- ### Set Default Versions and Verify Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Set default versions for both Node.js and Rust, then verify the active versions. ```bash $ nvm alias default v10.14.2 default -> v10.14.2 $ node --version v10.14.2 $ rustup default 1.31.0 1.31.0-x86_64-apple-darwin installed - rustc 1.31.0 (abe02cefd 2018-12-04) $ rustc --version rustc 1.31.0 (abe02cefd 2018-12-04) ``` -------------------------------- ### Running Rust Project with Cargo Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Demonstrates how to build and run a Rust project using the 'cargo run' command. ```bash $ cargo run Compiling hello-world v0.1.0 (/Users/pipo/workspace/rust-for-node-developers/package-manager/meta-data/rust) Finished dev [unoptimized + debuginfo] target(s) in 0.61s Running `target/debug/hello-world` Hello world! ``` -------------------------------- ### Configure Build Scripts in package.json Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Add 'build' and 'prepublishOnly' scripts to package.json. 'prepublishOnly' ensures the build process runs before publishing. ```json { "scripts": { "build": "tsc --build src", "prepublishOnly": "npm run build" } } ``` -------------------------------- ### Running Rust Project Quietly with cargo -q run Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Shows how to execute a Rust project with minimal Cargo output using the '-q' flag. ```bash $ cargo -q run Hello world! ``` -------------------------------- ### Basic Rust Hello World Source: https://github.com/unite-network/rust-for-node-developers/blob/master/README.md A simple 'Hello World' program in Rust, demonstrating the basic structure of a Rust executable. ```rust fn main() { println!("Hello World!"); } ``` -------------------------------- ### Package.json Main and Typings Fields Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Specify the main entry point for the compiled JavaScript and the location of declaration files. ```json { "main": "dist/index.js", "typings": "dist/index.d.ts" } ``` -------------------------------- ### Reading and Writing Files in Rust Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Shows how to read the entire content of a file into a String and how to write a String to a file. Includes necessary imports for file operations and error handling. ```rust use std::error::Error; use std::fs::File; use std::io::{Read,Write}; use std::str::from_utf8; fn read_file(path: &str) -> Result> { let mut file = File::open(path)?; let stat = file.metadata()?; let mut buffer = vec![0; stat.len() as usize]; file.read(&mut buffer)?; let value = from_utf8(&buffer)?.to_string(); Ok(value) } fn write_file(path: &str, data: &str) -> Result<(), Box> { File::create(path)?.write_all(data.as_bytes())?; Ok(()) } fn main() { let hello = read_file("hello.txt").unwrap(); let world = read_file("world.txt").unwrap(); let hello_world = format!("{} {}!", hello, world); write_file("hello-world.txt", &hello_world).unwrap(); println!("Wrote file 'hello-world.txt' with content: {}", hello_world); } ``` -------------------------------- ### Rust Hello World Source: https://github.com/unite-network/rust-for-node-developers/blob/master/hello-world/README.md The 'Hello World' program in Rust. It requires a main function as the entry point and uses a macro for printing. ```rust fn main() { println!("Hello world!"); } ``` -------------------------------- ### Basic JavaScript Hello World Source: https://github.com/unite-network/rust-for-node-developers/blob/master/README.md A basic 'Hello World' function in JavaScript, provided for comparison with the Rust equivalent. ```js function main() { console.log('Hello World!'); } ``` -------------------------------- ### Node.js Hello World Source: https://github.com/unite-network/rust-for-node-developers/blob/master/hello-world/README.md A simple 'Hello World' script for Node.js. This code is executed directly by the Node.js runtime. ```javascript console.log('Hello world!'); ``` -------------------------------- ### Publishing a Package with npm Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Command to publish your package to the npm registry. This will also trigger pre-publish scripts like build. ```bash $ npm publish > rfnd-hello-world@1.0.1 prepublishOnly . > npm run build > rfnd-hello-world@1.0.1 build /Users/pipo/workspace/rust-for-node-developers/package-manager/publishing/node > tsc --build src ``` -------------------------------- ### Rust Main Function with Dependency Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Uses and prints a constant from the 'rfnd-hello-world' crate in a Rust program. ```rust use rfnd_hello_world::HELLO_WORLD; fn main() { println!("Required: {}.", HELLO_WORLD); } ``` -------------------------------- ### Rust: Building a String with push_str Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Demonstrates how to build a mutable String by appending string slices using the push_str method. Requires the String to be declared as mutable. ```rust fn main() { let hello = read_file("hello.txt").unwrap(); let world = read_file("world.txt").unwrap(); let mut hello_world = String::new(); hello_world.push_str(&hello); hello_world.push_str(" "); hello_world.push_str(&world); hello_world.push_str("!"); println!("Content is: {}", hello_world); } ``` -------------------------------- ### Node.js HTTP Request Execution Source: https://github.com/unite-network/rust-for-node-developers/blob/master/http-requests/README.md Demonstrates running a Node.js script to send an HTTP request and view the JSON response. ```bash $ npm run -s start Response: {"login":"donaldpipowitch","id":1152805, ... ``` -------------------------------- ### Running the Rust Program Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Command to compile and run the Rust program from the terminal. ```bash $ cargo -q run ``` -------------------------------- ### Running the Node.js File Writing Script Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Execute this command in your terminal to run the Node.js script and verify its output. ```bash $ npm -s start Wrote file in hello-world.txt with content: Hello world! ``` -------------------------------- ### Import and Use Node.js Dependency Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Imports and logs a value from the 'rfnd-hello-world' package in a Node.js TypeScript file. ```ts import { HELLO_WORLD } from 'rfnd-hello-world'; console.log(`Required "${HELLO_WORLD}".`); ``` -------------------------------- ### Opening a File in Rust Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Opens the file 'hello.txt' and handles potential errors using a `match` statement. The `file` variable is declared as mutable. ```rust let mut file = match File::open("hello.txt") { Err(err) => panic!("Couldn't open: {}", err.description()), Ok(value) => value, }; ``` -------------------------------- ### Complete Rust Program for File Reading Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md This snippet shows a full Rust program that opens, reads, and prints the content of a file. It includes error handling for file operations. ```rust use std::error::Error; use std::fs::File; use std::io::Read; use std::str::from_utf8; fn main() { let mut file = match File::open("hello.txt") { Err(err) => panic!("Couldn't open: {}", err.description()), Ok(value) => value, }; let stat = match file.metadata() { Err(err) => panic!("Couldn't get stat: {}", err.description()), Ok(value) => value, }; let mut buffer = vec![0; stat.len() as usize]; match file.read(&mut buffer) { Err(err) => panic!("Couldn't read: {}", err.description()), Ok(_) => (), }; let data = match from_utf8(&buffer) { Err(err) => panic!("Couldn't convert buffer to string: {}", err.description()), Ok(value) => value, }; println!("Content is: {}", data); } ``` -------------------------------- ### Cargo Publish Command Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Publishes the current crate to the crates.io registry. This is the equivalent of `npm publish`. ```bash cargo publish ``` -------------------------------- ### Add Rust Dependency to Cargo.toml Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Manually adds the 'rfnd-hello-world' crate as a dependency in a Rust project's Cargo.toml file. ```toml [dependencies] rfnd-hello-world = "1.0.1" ``` -------------------------------- ### Rust .gitignore File Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md This .gitignore file specifies directories and files to be ignored by version control, similar to how .npmignore works for npm packages. ```gitignore Cargo.lock target ``` -------------------------------- ### Rust Main Function with Inline Dependency Access Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Accesses a constant from the 'rfnd-hello-world' crate directly within the println! macro in Rust. ```rust fn main() { println!("Required: {}.", rfnd_hello_world::HELLO_WORLD); } ``` -------------------------------- ### Cargo Package Command Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Packages the current crate locally to inspect its contents before publishing. Similar to `npm pack`. ```bash cargo package ``` -------------------------------- ### TypeScript Source Code Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Define the exported constant 'HELLO_WORLD' using ES2015 module syntax. ```ts export const HELLO_WORLD = 'Hello world!'; ``` -------------------------------- ### Creating a Buffer for File Reading Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Allocates a mutable byte vector (`buffer`) with a size determined by the file's metadata, ready to hold the file's content. ```rust let mut buffer = vec![0; stat.len() as usize]; ``` -------------------------------- ### Complete Node.js package.json Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md The final package.json configuration for a Node.js project using external dependencies and build scripts. ```json { "name": "use-hello-world", "version": "0.1.0", "private": true, "main": "dist/index.js", "typings": "dist/index.d.ts", "scripts": { "start": "npm run build && node dist", "build": "tsc --build src" }, "devDependencies": { "typescript": "^3.2.2" }, "dependencies": { "rfnd-hello-world": "^1.0.1" } } ``` -------------------------------- ### Node.js package.json Dependencies Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Shows the structure of a package.json file including devDependencies and dependencies. ```json { "devDependencies": { "typescript": "^3.2.2" }, "dependencies": { "rfnd-hello-world": "^1.0.1" } } ``` -------------------------------- ### Extracting Response Body and Status in Rust Source: https://github.com/unite-network/rust-for-node-developers/blob/master/http-requests/README.md Demonstrates extracting the response body and then its status. This order is important due to Rust's ownership rules. ```rust let buf = res.into_body().concat2().wait().unwrap(); println!("Response: {}", from_utf8(&buf).unwrap()); let status = res.status(); ``` -------------------------------- ### Rust Main Function with Multiple Imports Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Imports multiple constants from the 'rfnd-hello-world' crate using curly braces syntax in Rust. ```rust use rfnd_hello_world::{HELLO_WORLD, SOME_OTHER_VALUE}; fn main() { println!("Required: {}.", HELLO_WORLD); println!("Also: {}.", SOME_OTHER_VALUE); } ``` -------------------------------- ### Rust Main Function Definition Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Defines the main function, the entry point for the Rust program execution. ```rust fn main() { // ... } ``` -------------------------------- ### Cargo Login Command Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Logs into the crates.io registry using an API key. This is equivalent to `npm login`. ```bash cargo login ``` -------------------------------- ### Set Default Rust Version Source: https://github.com/unite-network/rust-for-node-developers/blob/master/setup/README.md Set a specific Rust version as the default toolchain. ```bash $ rustup default 1.29.0 info: using existing install for '1.29.0-x86_64-apple-darwin' info: default toolchain set to '1.29.0-x86_64-apple-darwin' 1.29.0-x86_64-apple-darwin unchanged - rustc 1.29.0 (aa3ca1994 2018-09-11) ``` -------------------------------- ### Printing File Content Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Prints the successfully read and converted string content to the console. ```rust println!("Content is: {}", data); ``` -------------------------------- ### Update npm Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Run this command to update npm to the latest version. This ensures you have the most recent features and security patches. ```bash $ npm install -g npm ``` -------------------------------- ### String Concatenation in Rust Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Demonstrates concatenating strings using the `+` operator and the `format!` macro. The `format!` macro is often more readable for complex string constructions. ```rust fn main() { let hello = read_file("hello.txt").expect("Couldn't read 'hello.txt'."); let world = read_file("world.txt").expect("Couldn't read 'world.txt'."); let hello_world = hello + " " + &world + "!"; println!("Content is: {}", hello_world); } ``` ```rust fn main() { let hello = read_file("hello.txt").expect("Couldn't read 'hello.txt'."); let world = read_file("world.txt").expect("Couldn't read 'world.txt'."); let hello_world = format!("{} {}!", hello, world); println!("Content is: {}", hello_world); } ``` -------------------------------- ### Using unwrap() for Concise Error Handling Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md This snippet demonstrates the use of `unwrap()` to simplify error handling by exiting the program on error. It's common in tutorials but less so in production code due to the lack of custom error messages. ```rust fn read_file(path: &str) -> String { read_to_string(path).unwrap() } ``` -------------------------------- ### Generating package-lock.json Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Command to generate a package-lock.json file for a Node.js project, ensuring dependency consistency. ```bash $ npm install npm notice created a lockfile as package-lock.json. You should commit this file. up to date in 0.924s found 0 vulnerabilities ``` -------------------------------- ### Rust Executing Request and Handling Response Source: https://github.com/unite-network/rust-for-node-developers/blob/master/http-requests/README.md Executes a configured HTTP request using the hyper client and processes the response. It concatenates the body and prints it as a UTF-8 string. ```rust client .request(req) .and_then(|res| { let status = res.status(); let buf = res.into_body().concat2().wait().unwrap(); println!("Response: {}", from_utf8(&buf).unwrap()); ``` -------------------------------- ### Refactored File Reading with a Helper Function Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Introduces a `read_file` helper function to avoid duplicating error handling logic when reading multiple files. ```diff use std::error::Error; use std::fs::read_to_string; +fn read_file(path: &str) -> String { + let data = match read_to_string(path) { + Err(err) => panic!("Couldn't read: {}", err.description()), + Ok(data) => data, + }; + return data; +} fn main() { - let hello = match read_to_string("hello.txt") { - Err(err) => panic!("Couldn't read: {}", err.description()), - Ok(data) => data, - }; - - let world = match read_to_string("world.txt") { - Err(err) => panic!("Couldn't read: {}", err.description()), - Ok(data) => data, - }; + let hello = read_file("hello.txt"); + let world = read_file("world.txt"); println!("Content is: {} and {}", hello, world); } ``` -------------------------------- ### Rust Cargo.toml Dependencies Source: https://github.com/unite-network/rust-for-node-developers/blob/master/http-requests/README.md Add these dependencies to your Cargo.toml file to use hyper and hyper-tls for HTTP and HTTPS requests. ```toml [dependencies] hyper = "0.12.21" hyper-tls = "0.3.1" ``` -------------------------------- ### Rust Implicit Return in Function Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Demonstrates using an implicit return in Rust by omitting the `return` keyword and semicolon for the last expression in a function. ```diff fn read_file(path: &str) -> String { let data = match read_to_string(path) { Err(err) => panic!("Couldn't read: {}", err.description()), Ok(data) => data, }; - return data; + data } ``` -------------------------------- ### TypeScript Configuration (tsconfig.json) Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Configure TypeScript compiler options, including module format, output directory, and source map generation. ```json { "compilerOptions": { "module": "commonjs", "declaration": true, "outDir": "../dist", "sourceMap": true, "declarationMap": true } } ``` -------------------------------- ### Handle HTTP Response Status in Rust Source: https://github.com/unite-network/rust-for-node-developers/blob/master/http-requests/README.md Check for client and server errors in an HTTP response status. Panics on error. ```rust if status.is_client_error() { panic!("Got client error: {}", status.as_u16()); } if status.is_server_error() { panic!("Got server error: {}", status.as_u16()); } Ok(()) }) .map_err(|_err| panic!("Couldn't send request.")) ``` -------------------------------- ### Rust: Explicit Error Handling with Box Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Demonstrates explicit error handling for file operations using Result>. Errors are converted to Box using .into() and returned early. ```rust use std::error::Error; use std::fs::File; use std::io::Read; use std::str::from_utf8; fn read_file(path: &str) -> Result> { let mut file = match File::open(path) { Err(err) => return Err(err.into()), Ok(value) => value, }; let stat = match file.metadata() { Err(err) => return Err(err.into()), Ok(value) => value, }; let mut buffer = vec![0; stat.len() as usize]; match file.read(&mut buffer) { Err(err) => return Err(err.into()), Ok(_) => (), }; match from_utf8(&buffer) { Err(err) => return Err(err.into()), Ok(value) => Ok(value.to_string()), } } fn main() { let hello = read_file("hello.txt").unwrap(); let world = read_file("world.txt").unwrap(); println!("Content is: {} and {}", hello, world); } ``` -------------------------------- ### Converting Buffer to String Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Converts the byte buffer into a UTF-8 string slice using `from_utf8`. Errors during conversion are handled. ```rust let data = match from_utf8(&buffer) { Err(err) => panic!("Couldn't convert buffer to string: {}", err.description()), Ok(value) => value, }; ``` -------------------------------- ### Simplified File Reading with `read_to_string` Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Reads the entire content of a file into a string using `std::fs::read_to_string`. This is a high-level abstraction for reading text files. It returns a `Result` which can be handled to display the content or panic on error. ```rust use std::error::Error; use std::fs::read_to_string; fn main() { match read_to_string("hello.txt") { Err(err) => panic!("Couldn't read: {}", err.description()), Ok(data) => println!("Content is: {}", data), }; } ``` -------------------------------- ### Convert Buffer to String with Error Handling Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Converts a byte buffer to a string slice using `from_utf8`. Handles potential conversion errors by panicking and printing the error description. Useful when dealing with raw byte data that is expected to be valid UTF-8. ```rust let data = match from_utf8(&buffer) { Err(err) => panic!("Couldn't convert buffer to string: {}", err.description()), Ok(value) => value, }; println!("Content is: {}", data); ``` -------------------------------- ### Reading Multiple Files in Rust Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Reads the content of both 'hello.txt' and 'world.txt' and prints them concatenated. This version duplicates error handling logic. ```diff use std::error::Error; use std::fs::read_to_string; fn main() { - match read_to_string("hello.txt") { + let hello = match read_to_string("hello.txt") { Err(err) => panic!("Couldn't read: {}", err.description()), - Ok(data) => println!("Content is: {}", data), + Ok(data) => data, }; + let world = match read_to_string("world.txt") { + Err(err) => panic!("Couldn't read: {}", err.description()), + Ok(data) => data, + }; + println!("Content is: {} and {}", hello, world); } ``` -------------------------------- ### Simplified Rust File Reading Function Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Further simplifies the `read_file` function by directly returning the result of the `match` expression, leveraging Rust's expression-based nature. ```diff fn read_file(path: &str) -> String { - let data = match read_to_string(path) { - Err(err) => panic!("Couldn't read: {}", err.description()), - Ok(data) => data, - }; - data + match read_to_string(path) { + Err(err) => panic!("Couldn't read: {}", err.description()), + Ok(data) => data, + } } ``` -------------------------------- ### Synchronous File Reading in Node.js Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Read a file synchronously using 'fs.openSync', 'fs.fstatSync', and 'fs.readSync'. This approach provides more low-level control and is useful for multi-step file operations. ```typescript import { openSync, readSync, fstatSync, Stats } from 'fs'; let fileDescriptor: number; try { fileDescriptor = openSync('hello.txt', 'r'); } catch (err) { console.log(`Couldn't open: ${err.message}`); process.exit(1); } let stat: Stats; try { stat = fstatSync(fileDescriptor); } catch (err) { console.log(`Couldn't get stat: ${err.message}`); process.exit(1); } const buffer = Buffer.alloc(stat.size); try { readSync(fileDescriptor, buffer, 0, stat.size, null); } catch (err) { console.log(`Couldn't read: ${err.message}`); process.exit(1); } let data: string; try { data = buffer.toString(); } catch (err) { console.log(`Couldn't convert buffer to string: ${err.message}`); process.exit(1); } console.log(`Content is: ${data}`); ``` -------------------------------- ### Read, Concatenate, and Write Files in Node.js Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md Use this snippet to read multiple files, combine their content, and write the result to a new file. It includes basic error handling for file operations. ```typescript import { readFileSync, writeFileSync } from 'fs'; let hello: string; try { hello = readFileSync('hello.txt', 'utf8'); } catch (err) { throw `Couldn't read 'hello.txt'.`; } let world: string; try { world = readFileSync('world.txt', 'utf8'); } catch (err) { throw `Couldn't read 'world.txt'.`; } let helloWorld = `${hello} ${world}!`; try { writeFileSync('hello-world.txt', helloWorld); } catch (err) { throw `Couldn't write 'hello-world.txt'.`; } console.log(`Wrote file 'hello-world.txt' with content: ${helloWorld}`); ``` -------------------------------- ### Cargo.toml Configuration for Rust Edition Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Adds support for Rust 2018 edition to a Cargo.toml file, enabling new language features. ```toml edition = "2018" ``` -------------------------------- ### Parse GitHub API JSON Response in Node.js Source: https://github.com/unite-network/rust-for-node-developers/blob/master/parse-json/README.md This snippet shows how to fetch repositories from the GitHub API, parse the JSON response, and extract specific fields like name, description, and fork status. It includes defining a TypeScript type for the repository data. ```typescript import { get } from 'https'; const host = 'api.github.com'; const path = '/users/donaldpipowitch/repos'; function isClientError(statusCode: number) { return statusCode >= 400 && statusCode < 500; } function isServerError(statusCode: number) { return statusCode >= 500; } const headers = { 'User-Agent': 'Mercateo/rust-for-node-developers' }; type Repository = { name: string; description: string | null; fork: boolean; }; get({ host, path, headers }, (res) => { let buf = ''; res.on('data', (chunk) => (buf = buf + chunk)); res.on('end', () => { if (isClientError(res.statusCode)) { throw `Got client error: ${res.statusCode}`; } if (isServerError(res.statusCode)) { throw `Got server error: ${res.statusCode}`; } const repositories: Repository[] = JSON.parse(buf).map( ({ name, description, fork }) => ({ name, description, fork }) ); console.log('Result is:\n', repositories); }); }).on('error', (err) => { throw `Couldn't send request.`; }); ``` -------------------------------- ### Update Rust and Cargo Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Use rustup to update both your Rust compiler and Cargo to their latest versions simultaneously. ```bash $ rustup update ``` -------------------------------- ### Combining unwrap_or_else() with Panic Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md This snippet illustrates a mixed approach using `unwrap_or_else()` with a closure to provide a custom panic message, offering more control than `unwrap()` or `expect()` alone. ```rust fn read_file(path: &str) -> String { read_to_string(path).unwrap_or_else(|err| panic!("Couldn't read: {}", err.description())) } ``` -------------------------------- ### Rust Import Statement for String Conversion Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Imports the `from_utf8` function, used to convert a byte slice into a UTF-8 string slice. ```rust use std::str::from_utf8; ``` -------------------------------- ### Node.js Error Handling: Logging and Exiting Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md An alternative error handling pattern in Node.js that logs an error message and explicitly exits the process. ```typescript let someValue; try { someValue = getSomeValue(); } catch (err) { console.log(`Couldn't get value.`); process.exit(1); } ``` -------------------------------- ### Node.js Error Handling: Throwing Custom Messages Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md This pattern demonstrates throwing custom error messages within a try-catch block, allowing Node.js to handle process exiting. ```typescript let someValue; try { someValue = getSomeValue(); } catch (err) { throw `Couldn't get value.`; } ``` -------------------------------- ### Reading File Content into Buffer Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Reads the content of the file into the pre-allocated buffer. The `read` method is provided by the `Read` trait. ```rust match file.read(&mut buffer) { Err(err) => panic!("Couldn't read: {}", err.description()), Ok(_) => (), }; ``` -------------------------------- ### Returning Result for Library Error Handling Source: https://github.com/unite-network/rust-for-node-developers/blob/master/write-files/README.md This snippet outlines the structure for a library function that returns a `Result` to allow the calling program to handle errors, rather than exiting. ```rust fn read_file(path: &str) -> Result { // our code } ``` -------------------------------- ### Asynchronous File Reading in Node.js Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Read a file asynchronously using the 'fs.readFile' function. This method takes a file path, encoding, and a callback function to handle the data or errors. ```typescript import { readFile } from 'fs'; readFile('hello.txt', 'utf8', (err, data) => { if (err) { console.log(`Couldn't read: ${err.message}`); process.exit(1); } else { console.log(`Content is: ${data}`); } }); ``` -------------------------------- ### Rust Import Statement for File Module Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md Imports the `File` struct from the standard library's file system module (`std::fs`), enabling file operations. ```rust use std::fs::File; ``` -------------------------------- ### Rust Constant Declaration Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md Defines a public string constant in Rust. This is analogous to exporting a constant in TypeScript. ```rust pub const HELLO_WORLD: &str = "Hello world!"; ``` -------------------------------- ### Rust Import Statement for Error Trait Source: https://github.com/unite-network/rust-for-node-developers/blob/master/read-files/README.md This line imports the `Error` trait, which is necessary to use the `description()` method on I/O errors. ```rust use std::error::Error; ``` -------------------------------- ### Adding User-Agent Header to HTTPS Request Source: https://github.com/unite-network/rust-for-node-developers/blob/master/http-requests/README.md This snippet demonstrates how to add custom headers, specifically a 'User-Agent', to an HTTPS request. This is often required by APIs. ```diff import { get } from 'https'; const host = 'api.github.com'; const path = '/users/donaldpipowitch'; function isClientError(statusCode: number) { return statusCode >= 400 && statusCode < 500; } function isServerError(statusCode: number) { return statusCode >= 500; } +const headers = { + 'User-Agent': 'Mercateo/rust-for-node-developers' +}; -get({ host, path }, (res) => { +get({ host, path, headers }, (res) => { let buf = ''; ``` -------------------------------- ### Define Repository Struct for Deserialization Source: https://github.com/unite-network/rust-for-node-developers/blob/master/parse-json/README.md Defines a Rust struct named 'Repository' with fields for name, description, and fork status. The `#[derive(Deserialize, Debug)]` attribute enables automatic deserialization from JSON and allows the struct to be printed for debugging. ```rust #[derive(Deserialize, Debug)] struct Repository { name: String, description: Option, fork: bool, } ``` -------------------------------- ### Generated Declaration File Source: https://github.com/unite-network/rust-for-node-developers/blob/master/package-manager/README.md The TypeScript declaration file (.d.ts) generated from the source, including value type inference and source map reference. ```ts export declare const HELLO_WORLD = 'Hello world!'; //# sourceMappingURL=index.d.ts.map ```